Day1
题解:isap+费用流
最初连的边的费用为0,然后跑一遍最大流。在原图的基础上再加容量为inf,费用是W[i],最后加一个点限流,跑费用流即可。
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<queue> #define N 50000 #define inf 1000000000 using namespace std; int n,m,k; int next[N],point[N],v[N],remain[N],cost[N],tot,laste[N],dis[N]; int x[N],y[N],z[N],l[N],num[N],deep[N],cur[N],mincost,can[N]; void add(int x,int y,int z,int k) { tot++; next[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=z; cost[tot]=k; tot++; next[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0; cost[tot]=-k; } int addflow(int s,int t) { int now=t; int ans=inf; while (now!=s) { ans=min(ans,remain[laste[now]]); now=v[laste[now]^1]; } now=t; while (now!=s) { remain[laste[now]]-=ans; remain[laste[now]^1]+=ans; now=v[laste[now]^1]; } return ans; } void bfs(int s,int t) { for (int i=s;i<=t;i++) deep[i]=t; deep[t]=0; queue<int> p; p.push(t); while(!p.empty()) { int now=p.front(); p.pop(); for (int i=point[now];i!=-1;i=next[i]) if (deep[v[i]]==t&&remain[i^1]) { deep[v[i]]=deep[now]+1; p.push(v[i]); } } } int isap(int s,int t) { int ans=0; bfs(s,t); for (int i=s;i<=t;i++) cur[i]=point[i]; for (int i=s;i<=t;i++) num[deep[i]]++; int now=s; while (deep[now]<t) { if (now==t) { ans+=addflow(s,t); now=s; } bool f=false; for (int i=cur[now];i!=-1;i=next[i]) if (deep[v[i]]+1==deep[now]&&remain[i]) { laste[v[i]]=i; cur[now]=i; f=true; now=v[i]; break; } if (!f) { int minn=t; for (int i=point[now];i!=-1;i=next[i]) if (remain[i]) minn=min(minn,deep[v[i]]); if (!--num[deep[now]]) break; deep[now]=minn+1; num[deep[now]]++; cur[now]=point[now]; if (now!=s) now=v[laste[now]^1]; } } return ans; } bool spfa(int s,int t) { for (int i=s;i<=t;i++) dis[i]=inf; memset(can,0,sizeof(can)); dis[s]=0; can[s]=1; queue<int> p; p.push(s); while (!p.empty()) { int now=p.front(); p.pop(); for (int i=point[now];i!=-1;i=next[i]) if(dis[v[i]]>dis[now]+cost[i]&&remain[i]) { dis[v[i]]=dis[now]+cost[i]; laste[v[i]]=i; if (!can[v[i]]) { can[v[i]]=1; p.push(v[i]); } } can[now]=0; } if (dis[t]==inf) return false; int add=addflow(s,t); mincost+=add*dis[t]; return true; } void maxflow(int s,int t) { while (spfa(s,t)); } int main() { scanf("%d%d%d",&n,&m,&k); memset(next,-1,sizeof(next)); memset(point,-1,sizeof(point)); tot=-1; for (int i=1;i<=m;i++) { scanf("%d%d%d%d",&x[i],&y[i],&z[i],&l[i]); add(x[i],y[i],z[i],0); } printf("%d ",isap(1,n)); for (int i=1;i<=m;i++) { add(x[i],y[i],inf,l[i]); } add(n,n+1,k,0); maxflow(1,n+1); printf("%d\n",mincost); }