Flow Problem HDU - 3549

 Flow Problem HDU - 3549 

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. 

InputThe 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)OutputFor 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



题意:网络流模版题,1到n的结点的最大的流
思路:用dinic可以过,为什么之前用sap的邻接矩阵和邻接表都wa或者T了呢

#include<stdio.h>
#include<iostream>
#include<map>
#include<string.h>
#include<queue>
#include<vector>
#include<math.h>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int dis[20];
int flow[500][500];
int n,m;
int bfs()
{
    memset(dis,-1,sizeof(dis));
    queue<int>Q;
    dis[1]=1;
    Q.push(1);
    while(!Q.empty())
    {
        int top=Q.front();
        Q.pop();
        for(int i=1;i<=n;i++)
        {
            if(flow[top][i]>0&&dis[i]<0)
            {
                dis[i]=dis[top]+1;
                Q.push(i);
            }
        }
    }
    if(dis[n]>0)return 1;
    return 0;
}
int dinic(int x,int k)
{
    if(x==n)
        return k;
    int y;
    for(int i=1;i<=n;i++)
    {
        if(flow[x][i]>0&&dis[i]==dis[x]+1&&(y=dinic(i,min(k,flow[x][i]))))
        {
            flow[x][i]-=y;
            flow[i][x]+=y;
            return y;
        }
    }
    return 0;
 
}
int main()
{
    int t;
    scanf("%d",&t);
    int cas=1;
    while(t--)
    {
        memset(flow,0,sizeof(flow));
        scanf("%d%d",&n,&m);
        int a,b,c;
        for(int i=0;i<m;i++)
        {
            scanf("%d%d%d",&a,&b,&c);
            flow[a][b]+=c;
        }
        int ans=0;
        while(bfs())
        {
            //cout<<"++"<<endl;
            int res;
            while(res=dinic(1,inf))ans+=res;
        }
        printf("Case %d: %d\n",cas++,ans);
    }
}
View Code

猜你喜欢

转载自www.cnblogs.com/smallhester/p/10295624.html
今日推荐