http://poj.org/problem?id=1273
最大流裸题 注意测试数据有重边的处理方法即可。
EK算法代码:
#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAX = 210;
const LL INF = 1e18;
LL map[MAX][MAX];
queue <int> Q;
int N,M,pre[MAX];
bool BFS(int S, int T){///判断是否有增广路
memset(pre, -1, sizeof(pre));
while(!Q.empty()) Q.pop();
Q.push(S);
while(!Q.empty()){
int u = Q.front();
Q.pop();
for(int i=1; i<=M; i++){
if(pre[i] == -1 && map[u][i] > 0){
pre[i] = u;
if(i == T) return true;
Q.push(i);
}
}
}
return false;
}
LL EK(int S, int T){///求解最大流
LL maxflow = 0;
while(BFS(S, T)){
LL minflow = INF;
for(int i=T; i!=S; i=pre[i])
minflow = min(minflow, map[pre[i]][i]);
for(int i=T; i!=S; i=pre[i]){
map[pre[i]][i] -= minflow;
map[i][pre[i]] += minflow;
}
maxflow += minflow;
}
return maxflow;
}
int main(){
while(scanf("%d%d",&N,&M) == 2){
memset(map, 0, sizeof(map));
int S = 1, T = M;
int u,v;
LL cap;
for(int i=0; i<N; i++){
scanf("%d%d%lld",&u,&v,&cap);
map[u][v] += cap;
}
printf("%lld\n",EK(S,T));
}
return 0;
}
Dinik算法代码
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace std;
const int MAX = 250;
const int INF = 0x3f3f3f3f;
int map[MAX][MAX],level[MAX],N,M;
queue <int> Q;
bool BFS(){///构建层次图
memset(level, -1, sizeof(level));
level[1] = 0;
Q.push(1);
while(!Q.empty()){
int u = Q.front();
Q.pop();
for(int i=1; i<=M; i++){
if(level[i] == -1 && map[u][i] > 0){
level[i] = level[u] + 1;
Q.push(i);
}
}
}
if(level[M] > 0) return true;
return false;
}
int DFS(int id, int minflow){///计算增广路上最小的流量值
if(id == M) return minflow;
int a = 0;
for(int i=1; i<=M; i++){
if(map[id][i] && level[i] == level[id] + 1
&& (a = DFS(i, min(map[id][i], minflow)))){
map[id][i] -= a;
map[i][id] += a;
return a;
}
}
return 0;
}
int main(){
while(scanf("%d%d",&N,&M) == 2){
memset(map, 0, sizeof(map));
for(int i=0; i<N; i++){
int u,v,cap;
scanf("%d%d%d",&u,&v,&cap);
map[u][v] += cap;
}
int tmp, ans = 0;
while(BFS()){///BFS为假时代表汇点不在层次图中 无法进行增广过程
while(tmp = DFS(1, INF)) ans += tmp;///累加每次增广路上增大的流量值
}
printf("%d\n",ans);
}
return 0;
}