Helvetic Coding Contest 2017 online mirror N. April Fools' Problem (medium) (费用流)
题目链接:Helvetic Coding Contest 2017 online mirror N. April Fools' Problem (medium)
题意:
有n天,每天产生一个想法要价值a[i],打印一个想法要b[i],
现在要打印出k个想法,必须要先产生才能打印,问最小的费用。
这里n不大的时候可以直接跑费用流。
见图看代码。
1 #include<bits/stdc++.h> 2 #define pb push_back 3 #define ls l,m,rt<<1 4 #define rs m+1,r,rt<<1|1 5 #define mst(a,b) memset(a,b,sizeof(a)) 6 #define F(i,a,b) for(int i=(a);i<=(b);++i) 7 #define ___ freopen("c:\\code\\in.txt","r",stdin); 8 using namespace std; 9 typedef long long ll; 10 11 const int N=2300; 12 13 namespace MCMF 14 { 15 const int N=5e6+7; 16 const ll inf=1ll<<62; 17 int u[N],v[N],cost[N],cap[N],g[N],nxt[N],ed,a[N],n; 18 int S,T,Q[N],flow,inq[N],p[N],now=1; 19 ll sumcost,d[N]; 20 21 void adg(int s,int t,int c,int co) 22 { 23 int &x=ed; 24 u[x]=s,v[x]=t,cap[x]=c,cost[x]=co,nxt[x]=g[s],g[s]=x,x++; 25 u[x]=t,v[x]=s,cap[x]=0,cost[x]=-co,nxt[x]=g[t],g[t]=x,x++; 26 } 27 void init(int _n) 28 { 29 S=_n+1,T=_n+2,n=T,ed=0; 30 for(int i=0;i<=n;i++)g[i]=-1; 31 } 32 bool spfa() 33 { 34 for(int i=0;i<=n;i++)d[i]=inf; 35 d[S]=0,inq[S]=now,p[S]=0,a[S]=INT_MAX; 36 int head=1,tail=1;Q[1]=S; 37 while(head<=tail) 38 { 39 int x=Q[head++]; 40 inq[x]--; 41 if(x==T)continue; 42 for(int i=g[x];~i;i=nxt[i]) 43 { 44 if(cap[i]>0&&d[v[i]]>d[x]+cost[i]) 45 { 46 d[v[i]]=d[x]+cost[i]; 47 p[v[i]]=i,a[v[i]]=min(a[x],cap[i]); 48 if(inq[v[i]]<now)inq[v[i]]=now,Q[++tail]=v[i]; 49 } 50 } 51 } 52 if(d[T]==inf)return 0; 53 flow+=a[T],sumcost+=d[T]*a[T]; 54 int x=T; 55 while(x!=S)cap[p[x]]-=a[T],cap[p[x]^1]+=a[T],x=u[p[x]]; 56 return 1; 57 } 58 ll mcmf() 59 { 60 flow=sumcost=0; 61 while(spfa())now++; 62 return sumcost; 63 } 64 } 65 int k,n,a[N],b[N],now; 66 int main(){ 67 scanf("%d%d",&n,&k); 68 F(i,1,n)scanf("%d",a+i); 69 F(i,1,n)scanf("%d",b+i); 70 MCMF::init(2*n+1); 71 int node=2*n+1; 72 MCMF::adg(MCMF::S,node,k,0); 73 F(i,1,n)MCMF::adg(node,i,1,a[i]); 74 F(i,1,n)MCMF::adg(i,i+n,1,0); 75 F(i,1,n-1)MCMF::adg(i+n,i+n+1,N,0); 76 F(i,1,n)MCMF::adg(i+n,MCMF::T,1,b[i]); 77 printf("%lld\n",MCMF::mcmf()); 78 return 0; 79 }