HDOJ-3549 Flow Problem (最大流模板)

来源:互联网 发布:姚明41分比赛数据 编辑:程序博客网 时间:2024/06/06 07:46

Flow Problem
Time Limit: 5000/5000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)

Problem Description
Network flow is a well-known difficult problem for ACMers. Given a graph, your task is to find out the maximum flow for the weighted directed graph.

Input
The first line of input contains an integer T, denoting the number of test cases.
For each test case, the first line contains two integers N and M, denoting the number of vertexes and edges in the graph. (2 <= N <= 15, 0 <= M <= 1000)
Next M lines, each line contains three integers X, Y and C, there is an edge from X to Y and the capacity of it is C. (1 <= X, Y <= N, 1 <= C <= 1000)

Output
For each test cases, you should output the maximum flow from source 1 to sink N.

Sample Input
2
3 2
1 2 1
2 3 1
3 3
1 2 1
2 3 1
1 3 1

Sample Output
Case 1: 1
Case 2: 2

代码

#include<bits\stdc++.h>using namespace std;const int N = 20;const int INF = 0x3f3f3f3f;int Capacity[N][N], ActualFlow[N][N];//最大容量和实际流量int flow[N];//每个节点当前流量int pre[N]; //int n, m, x, y, c;int bfs() {    memset(flow, 0, sizeof(flow));    memset(pre, 0, sizeof(pre));    queue<int> q;    q.push(1);    flow[1] = INF;//起点有无限流量    while (!q.empty()) {        int cur = q.front(); q.pop();        for (int i = 1; i <= n; i++) {            if (flow[i] == 0 && ActualFlow[cur][i] < Capacity[cur][i]) {                //如果该点还未饱和,更新该点的流量                flow[i] = min(flow[cur], Capacity[cur][i] - ActualFlow[cur][i]);                //取前一个点的最大流量和此条路的残余流量中小的一个                pre[i] = cur;                q.push(i);            }        }    }    return flow[n];//返回n点的最大流量}int EK() {    int res = 0;    int increasement,pos;    memset(ActualFlow, 0, sizeof(ActualFlow));    while (1) {        increasement = bfs();//每次获得一点增加        res += increasement;        if (increasement == 0)//当不能获得增加时,退出            return res;        pos = n;//从汇点开始更新        //更新到起点为止        while (pos != 1) {            ActualFlow[pre[pos]][pos] += increasement;            ActualFlow[pos][pre[pos]] -= increasement;//!!!重点,给了程序反悔的机会            pos = pre[pos];        }    }}int main() {    int cases; cin >> cases;    for(int i = 1; i <= cases; i++) {        memset(Capacity, 0, sizeof(Capacity));        scanf("%d%d", &n, &m);        while (m--) {            scanf("%d%d%d", &x, &y, &c);            Capacity[x][y] += c;        }        printf("Case %d: %d\n", i, EK());    }}
原创粉丝点击