HDOJ 3549 Flow Problem(最大流)

来源:互联网 发布:网络促销手段 编辑:程序博客网 时间:2024/06/10 16:45

Flow 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

23 21 2 12 3 13 31 2 12 3 11 3 1

Sample Output

Case 1: 1Case 2: 2

题目大意:网络流模板题

解题思路:dinic algorithm

代码如下:

#include <cstdio>#include <iostream>#include <cstring>#include <queue>#include <vector>#define INF 1e9using namespace std;const int maxn = 25;const int maxm = 2005;struct Edge{    int to,next,flow,cap;}edge[maxm];int head[maxn],level[maxn],cur[maxn];int n,m,cnt;void init(){    cnt = 0;    memset(head,-1,sizeof(head));}void add_edge(int from,int to,int cap){    edge[cnt].cap = cap;    edge[cnt].to = to;    edge[cnt].flow = 0;    edge[cnt].next = head[from];    head[from] = cnt++;}bool bfs(int s,int t){    queue<int> que;    memset(level,-1,sizeof(level));    level[s] = 0;    que.push(s);    while(que.size()){        int u = que.front();        que.pop();        for(int i = head[u];~i;i = edge[i].next){            int v = edge[i].to;            if(level[v] == -1 && edge[i].cap > edge[i].flow){                level[v] = level[u] + 1;                que.push(v);            }        }    }    return level[t] == -1 ? false : true;}int dfs(int u,int t,int low){    if(u == t) return low;    int ret = 0,temp;    for(int &it = cur[u];~it && ret < low;it = edge[it].next){        int v = edge[it].to;        if(level[v] == level[u] + 1 && edge[it].cap > edge[it].flow){            if(temp = dfs(v,t,min(low - ret,edge[it].cap - edge[it].flow))){                ret += temp;                edge[it].flow += temp;                edge[it ^ 1].flow -= temp;            }        }    }    if(!ret) level[u] = -1;    return ret;}int dinic(int s,int t){    int maxflow = 0,temp;    while(bfs(s,t)){        memcpy(cur,head,sizeof(head));        while(temp = dfs(s,t,INF)) maxflow += temp;    }    return maxflow;}int main(void){    int a,b,c,t,ncase = 0;    cin >> t;    while(t--){        cin >> n >> m;        init();        for(int i = 0;i < m;i++){            cin >> a >> b >> c;            add_edge(a-1,b-1,c);            add_edge(b-1,a-1,0);        }        int ans = dinic(0,n-1);        cout << "Case " << ++ncase << ": " <<  ans << endl;    }    return 0;}


0 0
原创粉丝点击