1834: [ZJOI2010]network 網絡擴容
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int N=3005;
const int M=100005;
const int inf=1e9;
int n,m,K,cnt=1,ans;
int from[M],to[M],nxt[M],lj[N],w[M],v[M],p[M];
void add(int f,int t,int ww,int vv)
{
cnt++,from[cnt]=f,to[cnt]=t,nxt[cnt]=lj[f],lj[f]=cnt,w[cnt]=ww,v[cnt]=vv;
cnt++,from[cnt]=t,to[cnt]=f,nxt[cnt]=lj[t],lj[t]=cnt,w[cnt]=0,v[cnt]=-vv;
}
queue<int>Q;
int d[N],bef[N],S;
bool vis[N];
bool bfs()
{
memset(d,0,sizeof d);
d[1]=1;
Q.push(1);
while(!Q.empty())
{
int x=Q.front();
Q.pop();
for(int i=lj[x];i;i=nxt[i])
if(w[i]&&!d[to[i]])
{
d[to[i]]=d[x]+1;
Q.push(to[i]);
}
}
if(d[n]) return true;
return false;
}
int dfs(int x,int v)
{
if(x==n||v==0) return v;
int ret=0;
for(int i=lj[x];i;i=nxt[i])
if(d[to[i]]==d[x]+1)
{
int f=dfs(to[i],min(v,w[i]));
w[i]-=f;
w[i^1]+=f;
v-=f;
ret+=f;
if(v==0) break;
}
if(ret==0) d[x]=-1;
return ret;
}
void Dinic()
{
while(bfs()) ans+=dfs(1,inf);
}
bool Spfa()
{
for(int i=0;i<=n;i++) d[i]=inf;
d[S]=0;
Q.push(S);
while(!Q.empty())
{
int x=Q.front();
Q.pop();
vis[x]=false;
for(int i=lj[x];i;i=nxt[i])
if(d[to[i]]>d[x]+v[i]&&w[i])
{
d[to[i]]=d[x]+v[i];
bef[to[i]]=i;
if(!vis[to[i]])
{
vis[to[i]]=true;
Q.push(to[i]);
}
}
}
if(d[n]!=inf) return true;
else return false;
}
void Build()
{
S=0;
add(S,1,K,0);
for(int i=1;i<=m;i++) add(from[i<<1],to[i<<1],inf,p[i]);
}
void Exflow()
{
ans=0;
while(Spfa())
{
int x=n,cost=0,flow=inf,sid;
while(x!=S)
{
sid=bef[x];
cost+=v[sid];
flow=min(flow,w[sid]);
x=from[sid];
}
ans+=cost*flow;
x=n;
while(x!=S)
{
sid=bef[x];
w[sid]-=flow;
w[sid^1]+=flow;
x=from[sid];
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&K);
int x,y,z;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d%d",&x,&y,&z,&p[i]);
add(x,y,z,0);
}
Dinic();
printf("%d ",ans);
Build();
Exflow();
printf("%d\n",ans);
}
Description
Input
Output
Sample Input
1 2 5 8
2 5 9 9
5 1 6 2
5 1 1 8
1 2 8 7
2 5 4 9
1 2 1 1
1 4 2 1
Sample Output
30%的數據中,N<=100
100%的數據中,N<=1000,M<=5000,K<=10