zoukankan      html  css  js  c++  java
  • 题解 CF802C Heidi and Library (hard)

    题目:CF802C Heidi and Library (hard)

    拆点费用流。。假设我们先把所有的买进来,再把没用的卖掉。。

    然后我们拆点,

    s -> i 费用为当天价格 流量为1

    i+n -> t 费用为0 流量为1

    i -> i+n 费用为0 流量为1

    此时流入=流出 最大流一定为n

    费用限制:

    i -> i+1 费用为0 流量为k-1 k-1表示可以不扔留到明天,但是明天的数也要留个位置

    每天想上一个a[i]出现的位置连一条费用为-c[a[i]],流量为1的边,表示在已有本书的情况下可以卖掉这本书。

     1 #include<stdio.h>
     2 #define it register int
     3 #define il inline
     4 typedef long long ll;
     5 const int N=1000005;
     6 const int inf=2e9;
     7 int h[N],nxt[N],adj[N],w[N],c[N],t=1,pre[N],a[N],cost[N],s,e,n,top1,top2,q[N],k;
     8 bool inq[N];
     9 ll d[N],ans;
    10 il int Min(it p,it q){
    11     return p<q?p:q;
    12 }
    13 il void add(it u,it v,it fl,it x){
    14     nxt[++t]=h[u],h[u]=t,adj[t]=v,w[t]=x,c[t]=fl,nxt[++t]=h[v],h[v]=t,adj[t]=u,w[t]=-x,c[t]=0;
    15 }
    16 il bool spfa(){
    17     for(it i=s;i<=e;++i) a[i]=pre[i]=inq[i]=0,d[i]=inf;
    18     top1=0,top2=1,d[s]=0,a[s]=inf;
    19     while(top1<top2){
    20         it top=q[++top1];inq[top]=false;
    21         for(it i=h[top];i;i=nxt[i])
    22             if(c[i]&&d[adj[i]]>d[top]+w[i]){
    23                 d[adj[i]]=d[top]+w[i],a[adj[i]]=Min(a[top],c[i]),pre[adj[i]]=i;
    24                 if(!inq[adj[i]]) inq[adj[i]]=true,q[++top2]=adj[i];
    25             }
    26     } 
    27     if(d[e]==inf) return false;
    28     ans+=1ll*a[e]*d[e]; 
    29     for(it i=e;i!=s;i=adj[pre[i]^1]) c[pre[i]]-=a[e],c[pre[i]^1]+=a[e];
    30     return true;
    31 }
    32 il void fr(int &num){
    33     num=0;char c=getchar();int p=1;
    34     while(c<'0'||c>'9') c=='-'?p=-1,c=getchar():c=getchar();
    35     while(c>='0'&&c<='9') num=num*10+c-'0',c=getchar();
    36     num*=p;
    37 }
    38 int main(){ 
    39     fr(n),fr(k),e=n<<1|1,s=0;
    40     for(it i=1;i<=n;++i) fr(a[i]),add(i,i+n,1,0),add(i+n,e,1,0);
    41     for(it i=1;i<=n;++i) fr(cost[i]);
    42     for(it i=1;i<=n;++i){
    43         add(s,i,1,cost[a[i]]);
    44         if(pre[a[i]]) add(i-1,pre[a[i]]+n,1,-cost[a[i]]);
    45         pre[a[i]]=i;
    46     }
    47     for(it i=1;i<n;++i) add(i,i+1,k-1,0);
    48     while(spfa()); 
    49     printf("%lld",ans);
    50     return 0;
    51 }
    View Code
     
  • 相关阅读:
    734. Sentence Similarity
    Rainbow Sort
    692. Top K Frequent Words
    347. Top K Frequent Elements
    12. Integer to Roman
    13. Roman to Integer
    109. Convert Sorted List to Binary Search Tree
    用表单写兴趣爱好的程序
    方法重载与方法重写的区别
    super和this的区别
  • 原文地址:https://www.cnblogs.com/Kylin-xy/p/11742390.html
Copyright © 2011-2022 走看看