BZOJ1834:[ZJOI2010]网络扩容——题解
http://www.lydsy.com/JudgeOnline/problem.php?id=1834
https://www.luogu.org/problemnew/show/P2604#sub
给定一张有向图,每条边都有一个容量C和一个扩容费用W。这里扩容费用是指将容量扩大1所需的费用。求: 1、 在不扩容的情况下,1到N的最大流; 2、 将1到N的最大流增加K所需的最小扩容费用。
大水题,按照题意建图就可以完成第一问,然后对着残余网络换终点为T,n到T连容量为k的边,其他的点的路径再连容量INF费用为w的边跑费用流即可。
#include<cstdio> #include<iostream> #include<queue> #include<cstring> #include<algorithm> #include<cctype> using namespace std; typedef long long ll; const int INF=1e9; const int N=1010,M=30010; inline int read(){ int X=0,w=0;char ch=0; while(!isdigit(ch)){w|=ch=='-';ch=getchar();} while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar(); return w?-X:X; } inline int getc(){ char ch=0; while(!isdigit(ch))ch=getchar(); return ch^48; } struct node{ int nxt,to,w,b; }edge[M]; int head[N],cnt=-1; inline void add(int u,int v,int w,int b){ edge[++cnt].to=v;edge[cnt].w=w;edge[cnt].b=b; edge[cnt].nxt=head[u];head[u]=cnt; edge[++cnt].to=u;edge[cnt].w=0;edge[cnt].b=-b; edge[cnt].nxt=head[v];head[v]=cnt; } int dis[N]; bool vis[N]; inline bool spfa(int s,int t,int n){ deque<int>q; memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++)dis[i]=INF; dis[t]=0;q.push_back(t);vis[t]=1; while(!q.empty()){ int u=q.front(); q.pop_front();vis[u]=0; for(int i=head[u];i!=-1;i=edge[i].nxt){ int v=edge[i].to; int b=edge[i].b; if(edge[i^1].w&&dis[v]>dis[u]-b){ dis[v]=dis[u]-b; if(!vis[v]){ vis[v]=1; if(!q.empty()&&dis[v]<dis[q.front()]){ q.push_front(v); }else{ q.push_back(v); } } } } } return dis[s]<INF; } int ans,cur[N]; int dfs(int u,int flow,int m){ if(u==m){ vis[m]=1; return flow; } int res=0,delta; vis[u]=1; for(int &e=cur[u];e!=-1;e=edge[e].nxt){ int v=edge[e].to; int b=edge[e].b; if(!vis[v]&&edge[e].w&&dis[u]-b==dis[v]){ delta=dfs(v,min(edge[e].w,flow-res),m); if(delta){ edge[e].w-=delta; edge[e^1].w+=delta; res+=delta; ans+=delta*b; if(res==flow)break; } } } return res; } inline int costflow(int S,int T,int n){ int flow=0; while(spfa(S,T,n)){ do{ for(int i=1;i<=n;i++)cur[i]=head[i]; memset(vis,0,sizeof(vis)); flow+=dfs(S,INF,T); }while(vis[T]); } return flow; } struct data{ int u,v,c,w; }q[M]; int main(){ memset(head,-1,sizeof(head)); int n=read(),m=read(),k=read(),S=1,T=n; for(int i=1;i<=m;i++){ q[i].u=read(),q[i].v=read(); q[i].c=read(),q[i].w=read(); add(q[i].u,q[i].v,q[i].c,0); } printf("%d ",costflow(S,T,T)); for(int i=1;i<=m;i++){ add(q[i].u,q[i].v,INF,q[i].w); } T=n+1;add(n,T,k,0); costflow(S,T,T); printf("%d\n",ans); return 0; }
+++++++++++++++++++++++++++++++++++++++++++
+本文作者:luyouqi233。 +
+欢迎访问我的博客:http://www.cnblogs.com/luyouqi233/+
+++++++++++++++++++++++++++++++++++++++++++