[BZOJ1834][ZJOI2010]network 網絡擴容
阿新 • • 發佈:2018-01-01
() 輸出 true void i++ http cos class min
BZOJ
Luogu
Description
給定一張有向圖,每條邊都有一個容量C和一個擴容費用W。這裏擴容費用是指將容量擴大1所需的費用。求: 1、 在不擴容的情況下,1到N的最大流; 2、 將1到N的最大流增加K所需的最小擴容費用。
Input
輸入文件的第一行包含三個整數N,M,K,表示有向圖的點數、邊數以及所需要增加的流量。 接下來的M行每行包含四個整數u,v,C,W,表示一條從u到v,容量為C,擴容費用為W的邊。
Output
輸出文件一行包含兩個整數,分別表示問題1和問題2的答案。
Sample Input
5 8 2
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
13 19
30%的數據中,N<=100
100%的數據中,N<=1000,M<=5000,K<=10
題解
第一問裸的Dinic
第二問再加入容量為K費用為W的邊,可以在原圖上面跑,因為是不影響的。
code
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 5005;
const int inf = 1e9 ;
struct edge{int to,next,w,cost;}a[N<<2];
int n,m,k,s,t,U[N],V[N],C[N],W[N],head[N],cnt=1,dep[N],cur[N],dis[N],vis[N],pe[N],ans;
queue<int>Q;
int gi()
{
int x=0,w=1;char ch=getchar();
while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if (ch=='-' ) w=0,ch=getchar();
while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return w?x:-x;
}
void link(int u,int v,int w,int cost)
{
a[++cnt]=(edge){v,head[u],w,cost};
head[u]=cnt;
a[++cnt]=(edge){u,head[v],0,-cost};
head[v]=cnt;
}
bool bfs()
{
memset(dep,0,sizeof(dep));
dep[1]=1;Q.push(1);
while (!Q.empty())
{
int u=Q.front();Q.pop();
for (int e=head[u];e;e=a[e].next)
if (a[e].w&&!dep[a[e].to])
dep[a[e].to]=dep[u]+1,Q.push(a[e].to);
}
return dep[n];
}
int dfs(int u,int flow)
{
if (u==n)
return flow;
for (int &e=cur[u];e;e=a[e].next)
if (a[e].w&&dep[a[e].to]==dep[u]+1)
{
int temp=dfs(a[e].to,min(flow,a[e].w));
if (temp) {a[e].w-=temp;a[e^1].w+=temp;return temp;}
}
return 0;
}
int Dinic()
{
int res=0;
while (bfs())
{
for (int i=1;i<=n;i++) cur[i]=head[i];
while (int temp=dfs(1,inf)) res+=temp;
}
return res;
}
bool spfa()
{
memset(dis,63,sizeof(dis));
dis[n+1]=0;Q.push(n+1);
while (!Q.empty())
{
int u=Q.front();Q.pop();
for (int e=head[u];e;e=a[e].next)
{
int v=a[e].to;
if (a[e].w&&dis[v]>dis[u]+a[e].cost)
{
dis[v]=dis[u]+a[e].cost;pe[v]=e;
if (!vis[v]) vis[v]=1,Q.push(v);
}
}
vis[u]=0;
}
if (dis[n]==dis[0]) return false;
int sum=inf;
for (int i=n;i!=n+1;i=a[pe[i]^1].to)
sum=min(sum,a[pe[i]].w);
for (int i=n;i!=n+1;i=a[pe[i]^1].to)
a[pe[i]].w-=sum,a[pe[i]^1].w+=sum;
ans+=dis[n]*sum;
return true;
}
int main()
{
n=gi();m=gi();k=gi();
for (int i=1;i<=m;i++)
{
U[i]=gi();V[i]=gi();
C[i]=gi();W[i]=gi();
link(U[i],V[i],C[i],0);
}
link(n+1,1,k,0);
printf("%d ",Dinic());
for (int i=1;i<=m;i++)
link(U[i],V[i],k,W[i]);
while (spfa());
printf("%d\n",ans);
return 0;
}
[BZOJ1834][ZJOI2010]network 網絡擴容