您的位置:首页 > 其它

Dinic

2016-02-03 12:50 302 查看


多路增广+当前弧优化

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 210 << 1;
const int INF = 2000000010;
int n,m,tot(0),to[maxn],nxt[maxn],fir[maxn],rest[maxn],mark[maxn];

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 == n) return limit;
int used = 0,flow,i;
for (i = fir[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) mark[x]=-1;
return used;
}

bool bfs(){
memset(mark,-1,sizeof(mark));
queue <int> q;
int x;
mark[1] = 1;
q.push(1);
while (!q.empty()){
x = q.front();
q.pop();
for (int i = fir[x];i;i = nxt[i])
if (mark[to[i]] == -1 && rest[i])
{
q.push(to[i]);
mark[to[i]] = mark[x]+1;
}
}
return mark
!=-1;
}

int main(){
int u,v,w;
scanf("%d%d",&m,&n);
for (int i=0;i<m;i++){
scanf("%d%d%d",&u,&v,&w);
if (u != v) add(u,v,w);
}
int ans(0);
while (bfs()) ans += dfs(1,INF);
printf("%d\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: