Dinic

来源:互联网 发布:中国种植网域名交易 编辑:程序博客网 时间:2024/05/24 04:16

多路增广+当前弧优化

#include <bits/stdc++.h>using namespace std;const int maxn = 8000080;const int INF = 2100000010;int n,m,tot(0),to[maxn],nxt[maxn],fir[maxn],g[maxn],rest[maxn],mark[maxn],s,t;int curr[maxn];inline int read(){int s=0; char c=getchar();while (c<'0' || c>'9') c=getchar();while (c>='0' && c<='9') s=s*10+c-'0',c=getchar();return s;}void add(int u, int v, int w){to[++tot] = v; nxt[tot] = fir[u]; fir[u] = tot; rest[tot] = w;to[tot^1] = u; nxt[tot^1] = fir[v]; fir[v] = tot^1;rest[tot^1] = 0;tot++;}int dfs(int x,int limit){if (x == t) return limit;int used = 0,flow,i;for (i = curr[x];i && used<limit;i = nxt[i])if (mark[to[i]]==mark[x]+1 && rest[i]){flow = dfs(to[i],min(rest[i],limit-used));rest[i] -= flow;rest[i^1] += flow;used += flow;}if (used<limit) mark[x]=-1;curr[x] = i;return used;}bool bfs(){memset(mark,-1,sizeof(mark));for (int i = 1; i <= n; ++i) curr[i] = fir[i];queue <int> q;int x;mark[s] = 1;q.push(s);while (!q.empty()){x = q.front();q.pop();for (int i = fir[x];i;i = nxt[i])if (mark[to[i]] == -1 && rest[i]){mark[to[i]] = mark[x]+1;if (to[i]==t) return 1;q.push(to[i]);}}return mark[t]!=-1;}int main(){int u,v,w;n=read();m=read();s=read();t=read();for (int i=0;i<m;i++){u=read(),v=read(),w=read();if (u != v) add(u,v,w);}cerr << "!";int ans(0);while (bfs()) ans += dfs(s,INF);printf("%d\n",ans);return 0;}


0 0