Flow Problem HDU - 3549 Dinic

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<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int M = 1e5 + 10;
int t;
int n,m;
struct node
{
    int to,cap,rev;
};
vector<node>e[1100];//图的邻接表表示
int level[1100];//顶点到源点的距离标号
int iter[1100];//当前弧,在其之前的边没用
//增加一条从l到r容量为c的边
void init(int l,int r,int c)
{
    e[l].push_back((node){r,c,e[r].size()});
    e[r].push_back((node){l,0,e[l].size()-1});
}
//通过bfs计算从源点出发的距离标号
void bfs(int s)
{
    memset(level,-1,sizeof(level));
    queue<int>q;
    level[s]=0;
    q.push(s);
    while(!q.empty())
    {
        int v=q.front();
        q.pop();
        for(int i=0;i<e[v].size();i++)
        {
            node &ee=e[v][i];
           // cout<<ee.to<<" "<<ee.cap<<" "<<level[ee.to]<<" "<<level[v]+1<<endl;
            if(ee.cap>0&&level[ee.to]<0)
            {
                level[ee.to]=level[v]+1;
                q.push(ee.to);
            }
        }
    }
}
//通过dfs寻找增广路
int dfs(int v,int t,int f)
{
    if(v==t)
        return f;
    for(int &i=iter[v];i<e[v].size();i++)
    {
        node &ee=e[v][i];
        if(ee.cap>0&&level[v]<level[ee.to])
        {
            int d=dfs(ee.to,t,min(f,ee.cap));
            if(d>0)
            {
                //cout<<d<<"*"<<endl;
                ee.cap-=d;
                e[ee.to][ee.rev].cap+=d;
                return d;
            }
        }
    }
    return 0;
}
int max_flow(int s,int t)
{
    int ff=0;
    for(;;)
    {
        bfs(s);

        if(level[t]<0)
            return ff;
        //cout<<s<<" "<<t<<endl;
        memset(iter,0,sizeof(iter));
        int f;
        while((f=dfs(s,t,inf))>0){
            ff+=f;
        }
    }
}
int main()
{
    scanf("%d",&t);
    int k=1;
    while(t--)
    {
        memset(e,0,sizeof(e));
        scanf("%d%d",&n,&m);
        int l,r,c;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&l,&r,&c);
            init(l,r,c);
        }
        int ans=max_flow(1,n);
        printf("Case %d: %d\n",k++,ans);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/liluoyu_1016/article/details/80009565
今日推荐