您的位置:首页 > 大数据 > 人工智能

POJ 1273 Drainage Ditches 最大流

2014-02-19 23:27 393 查看
http://poj.org/problem?id=1273

题目大意:

给你N条路径(有重边),和M个点,求以1为源点,M为汇点的最大流。

思路:

第一题最大流问题,直接用Edmonds-Karp算法即可

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN = 1<<8;
int map[MAXN][MAXN];
int flow[MAXN];
int pre[MAXN];
int n, m;
int bfs(int s,int t)
{
memset(pre, -1, sizeof(pre));
queue<int> q;
q.push(s);
pre[s] = 0;
flow[s] = 0x3ffffff;

while (!q.empty())
{
int cur = q.front();
q.pop();
for (int i = 1; i <= m; i++)
{
if (map[cur][i] > 0 && pre[i] == -1)
{
flow[i] = min(flow[cur],map[cur][i]);
pre[i] = cur;
q.push(i);
}
}
}
return pre[t] == -1 ? -1 : flow[t];
}

int maxFlow(int s,int t)
{
int ans = 0;
int curFlow=0;
while ((curFlow=bfs(s,t))  !=-1)
{
int cur = t;
while (cur != s)
{
map[pre[cur]][cur] -= curFlow;
map[cur][pre[cur]] += curFlow;
cur = pre[cur];
}
ans += curFlow;
}
return ans;
}

int main()
{
while (~scanf("%d%d", &n, &m))
{
memset(map, 0, sizeof(map));
for (int i = 0; i < n; i++)
{
int from, to, val;
scanf("%d%d%d", &from, &to, &val);
map[from][to] += val;
}

printf("%d\n", maxFlow(1,m));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: