# HDU 3549 Flow Problem 网络流 基础题

317人阅读 评论(0)

DINIC求网络流最大流

#include<iostream>
#include<queue>
#include<cstdlib>
#include<vector>
#include<cstring>
#include<cstdio>
using namespace std;
const int INF = 0x7f7f7f7f;
const int MAXN = 20;
const int MAXM = 1005;
int n, m, s, t, cnt;
bool vis[MAXN];
int d[MAXN], cur[MAXN], que[MAXN];
struct edge_{
int from, to, cap, flow, next;
}edge[MAXM];

void init(){
memset(edge, -1, sizeof(edge));
cnt = 0;
}

void add(int from, int to, int cap){
edge[cnt].from = from, edge[cnt].to = to;
edge[cnt].cap = cap, edge[cnt].next = head[from];
edge[cnt].flow = 0;
edge[cnt].from = to, edge[cnt].to = from;
edge[cnt].cap = 0, edge[cnt].next = head[to];
edge[cnt].flow = 0;
}

bool bfs(){
memset(vis, false, sizeof(vis));
memset(d, 0, sizeof(d));
d[s] = 0, vis[s] = 1, que[0] = s;
int tail = 0, front = 1;
while(tail < front){
int x = que[tail++];
for(int now = head[x]; ~now; now = edge[now].next){
edge_ &e = edge[now];
if(!vis[e.to] && e.cap > e.flow){
vis[e.to] = 1;
d[e.to] = d[x] + 1;
que[front++] = e.to;
}
}
}
return vis[t];
}

int dfs(int x, int a){
if(x == t || a == 0)
return a;
int flow = 0, f;
for(int &now = cur[x]; ~now; now = edge[now].next){
edge_ &e = edge[now];
if(d[x] + 1 == d[e.to] && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0){
e.flow +=f;
edge[now ^ 1].flow -= f;
flow += f;
a -= f;
if(a == 0)
break;
}
}
return flow;
}

int maxFlow(int _s, int _t, int _n, int _m){
s = _s, t = _t;
n = _n, m = _m;
int flow = 0;
while(bfs()){
for(int i = 1; i <= n; i++)
flow += dfs(s, INF);
}
return flow;
}

int main(){
int n, m, s, t, c, ca = 1, num;
scanf("%d", &num);
while(num--){
init();
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++){
scanf("%d%d%d", &s, &t, &c);
}
printf("Case %d: %d\n", ca++, maxFlow(1, n, n, m));
}
return 0;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：29426次
• 积分：920
• 等级：
• 排名：千里之外
• 原创：65篇
• 转载：2篇
• 译文：0篇
• 评论：4条
阅读排行
评论排行
最新评论