HDU- 3549-Flow Problem (网络流之 EK)

Flow Problem



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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;

const int inf = 1e8;
int cap[50][50],flow[50][50],a[50],pre[50];
//cap 容量 flow 流量 a标记&&最小 pre 记录前驱
int t,n,m,x,y,c,maxflow,cas;


void bfs ()//找增广路
{
    queue <int >q;
    memset (flow,0,sizeof (flow));
    while (1)
    {
        memset (a,0,sizeof (a));
        pre[1] = -1;
        a[1] = inf;
        q.push (1);
        while (!q.empty())
        {
            int u = q.front();
            q.pop ();
            for (int v = 1; v <= n; v++)
            {
                if ( !a[v] && cap[u][v] > flow[u][v])
                {
                    q.push (v);
                    pre[v] = u;

                    a[v] = min (a[u],cap[u][v] - flow[u][v]);//1-->v的最小残量

                }
            }
        }

        if ( a[n] == 0)//找不到  目前已是最大流
            break;
        maxflow += a[n];
        for (int v = n; v != -1 ; v = pre[v])
        {
            flow[pre[v]][v] += a[n];///正向加
            flow[v][pre[v]] -= a[n];///反向减    为了给程序一个后悔的机会  因为BFS 找的可能不是当前最小
        }
    }
    printf ("Case %d: %d\n",cas++,maxflow);
}

int main()
{
    scanf ("%d",&t);
    cas = 1;
    while ( t-- )
    {
        maxflow = 0;
        scanf ("%d%d",&n,&m);
        memset (cap,0,sizeof (cap));
        for (int i = 0 ; i < m; i++)
        {
            scanf ("%d%d%d",&x,&y,&c);
            cap[x][y] += c;
        }
        bfs ();
    }
    return 0;
}




你可能感兴趣的:(HDU- 3549-Flow Problem (网络流之 EK))