HDU - 3549 Flow Problem(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

题意:输入t组数据,每组数据输入n个节点。m条边。输出从源点1到n的最大流量

简单最大流模板题。套个模板即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e4+10;
const int inf=0x7fffffff;
struct edge
{
    int to,val,rev;
    edge(){}
    edge(int a,int b,int c)
    {
        to=a;
        val=b;
        rev=c;
    }
};
vector<edge>mp[maxn];
void add(int from,int to,int val)
{
    mp[from].push_back(edge(to,val,mp[to].size()));
    mp[to].push_back(edge(from,0,mp[from].size()-1));
}
int t,n,m;
int dep[20];
int bfs()
{
    memset(dep,-1,sizeof dep);
    queue<int >q;
    while(!q.empty())q.pop();
    dep[1]=0;
    q.push(1);
    while(!q.empty())
    {
        int tmp=q.front();
        q.pop();
        if(tmp==n)return 1;
        for(int i=0;i<mp[tmp].size();i++)
        {
            int &to=mp[tmp][i].to,flow=mp[tmp][i].val;
            if(dep[to]==-1&&flow)
            {
                dep[to]=dep[tmp]+1;
                q.push(to);
            }
        }
    }
    return 0;
}
int dfs(int s,int t,int flow)
{
    if(s==t)return flow;
    int pre=0;
    for(int i=0;i<mp[s].size();i++)
    {
        int &to=mp[s][i].to,val=mp[s][i].val;
        if(dep[s]+1==dep[to]&&val>0)
        {
            int tmp=min(flow-pre,val);
            int sub=dfs(to,t,tmp);
            mp[s][i].val-=sub;
            mp[to][mp[s][i].rev].val+=sub;
            pre+=sub;
            if(pre==flow)return pre;
        }
    }
    return pre;
}
int dinic()
{
    int ans=0;
    while(bfs())ans+=dfs(1,n,inf);
    return ans;
}
int main()
{
    int cas=1;
    scanf("%d",&t);
    while(t--)
    {
        for(int i=0;i<=n;i++)mp[i].clear();
        int from,to,val;
        scanf("%d%d",&n,&m);
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&from,&to,&val);
            add(from,to,val);
        }
        printf("Case %d: %d\n",cas++,dinic());
    }
}

猜你喜欢

转载自blog.csdn.net/kuronekonano/article/details/80518432
今日推荐