BZOJ 1834: [ZJOI2010]network 网络扩容(网络流+费用流)

时间:2023-03-08 16:58:25
BZOJ 1834: [ZJOI2010]network 网络扩容(网络流+费用流)

一看就知道是模板题= = ,不说什么了= =

PS:回去搞期末了,暑假再来刷题了

CODE:

 #include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#define maxn 1010
#define maxm 20010
#define inf 0x7fffffff
using namespace std;
struct edges{
int to,next,cap,dist;bool b;
}edge[maxm];
int n,m,s,t,k,l;
int next[maxn],dist[maxn],way[maxn],h[maxn],p[maxn],gap[maxn];
bool b[maxn];
queue<int> q;
int addedge(int from,int to,int cap,int dist,bool bo){
l++;
edge[l*]=(edges){to,next[from],cap,dist,bo};
edge[l*+]=(edges){from,next[to],,-dist,bo};
next[from]=l*;next[to]=l*+;
return ;
}
bool spfa(){
memset(b,,sizeof(b));
for (int i=;i<=n;i++) dist[i]=inf;
dist[]=;
q.push();
while (!q.empty()){
int u=q.front();q.pop();
b[u]=;
for (int i=next[u];i;i=edge[i].next)
if (edge[i].cap&&dist[edge[i].to]>dist[u]+edge[i].dist) {
dist[edge[i].to]=dist[u]+edge[i].dist;
way[edge[i].to]=i;
if(!b[edge[i].to]){
b[edge[i].to]=;
q.push(edge[i].to);
}
}
}
if (dist[t]==inf) return ;
return ;
}
int mcmf(int cap){
int cost=;
while (spfa()){
int x=n,flow=inf;
while (x!=){
flow=min(flow,edge[way[x]].cap);
x=edge[way[x]^].to;
}
if (flow>=cap) return (cost+=dist[n]*cap);
cost+=dist[n]*flow;
cap-=flow;
x=n;
while(x!=){
edge[way[x]].cap-=flow;
edge[way[x]^].cap+=flow;
x=edge[way[x]^].to;
}
}
return cost;
}
int sap(int u,int flow){
if (u==t) return flow;
int cur=;
for (int i=p[u];i;i=edge[i].next)
if (edge[i].b&&edge[i].cap&&h[u]==h[edge[i].to]+){
int cut=sap(edge[i].to,min(flow-cur,edge[i].cap));
edge[i].cap-=cut;edge[i^].cap+=cut;
p[u]=i;
if ((cur+=cut)==flow ) return flow;
}
if (!(--gap[h[u]])) h[s]=n;
gap[++h[u]]++;
p[u]=next[u];
return cur;
}
int maxflow(){
memset(gap,,sizeof(gap));
memset(h,,sizeof(h));
gap[]=n;
for(int i=;i<=n;i++) p[i]=next[i];
int flow=;
while (h[s]<n) flow+=sap(s,inf);
return flow;
}
int main(){
scanf("%d%d%d",&n,&m,&k);
s=,t=n;
for (int i=;i<=m;i++) {
int x,y,cap,d;
scanf("%d%d%d%d",&x,&y,&cap,&d);
addedge(x,y,cap,,);
addedge(x,y,inf,d,);
}
int ans=maxflow();
printf("%d %d\n",ans,mcmf(k));
return ;
}