Poj--1495(最大流)

2014-12-20 14:35:38

思路:经典的最大流,添加一个总源点和总汇点即可。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cmath>
 5 #include <vector>
 6 #include <map>
 7 #include <set>
 8 #include <stack>
 9 #include <queue>
10 #include <iostream>
11 #include <algorithm>
12 using namespace std;
13 #define lp (p << 1)
14 #define rp (p << 1|1)
15 #define getmid(l,r) (l + (r - l) / 2)
16 #define MP(a,b) make_pair(a,b)
17 typedef long long ll;
18 typedef unsigned long long ull;
19 const int INF = 1 << 30;
20 const int maxn = 110;
21 
22 int n,np,nc,m,c[maxn][maxn],lev[maxn];
23 int Q[maxn],head,rear;
24 
25 void Bfs(){
26     memset(lev,-1,sizeof(lev));
27     Q[head = rear = 1] = 0;
28     lev[0] = 0;
29     while(head <= rear){
30         int x = Q[head++];
31         for(int i = 1; i <= n + 2; ++i) if(lev[i] < 0 && c[x][i] > 0){
32             lev[i] = lev[x] + 1;
33             Q[++rear] = i;
34         }
35     }
36 }
37 
38 int Dfs(int p,int minf){
39     if(p == n + 2) return minf;
40     for(int i = 1; i <= n + 2; ++i) if(lev[i] > lev[p] && c[p][i] > 0){
41         int d = Dfs(i,min(c[p][i],minf));
42         if(d > 0){
43             c[p][i] -= d;
44             c[i][p] += d;
45             return d; //发现增广路
46         }
47     }
48     return 0; //无增广路
49 }
50 
51 int Dinic(){
52     int max_flow = 0,plus;
53     while(1){
54         Bfs();
55         if(lev[n + 2] < 0) break;
56         while((plus = Dfs(0,INF)) > 0) max_flow += plus;
57     }
58     return max_flow;
59 }
60 
61 int main(){
62     int t1,t2,t3;
63     while(scanf("%d%d%d%d",&n,&np,&nc,&m) != EOF){
64         memset(c,0,sizeof(c));
65         for(int i = 1; i <= m; ++i){
66             scanf(" (%d,%d)%d",&t1,&t2,&t3);
67             c[++t1][++t2] += t3;
68         }
69         for(int i = 1; i <= np; ++i){
70             scanf(" (%d)%d",&t1,&t2);
71             c[0][++t1] += t2;
72         }
73         for(int i = 1; i <= nc; ++i){
74             scanf(" (%d)%d",&t1,&t2);
75             c[++t1][n + 2] += t2;
76         }
77         printf("%d\n",Dinic());
78     }
79     return 0;
80 }

 

posted @ 2014-12-20 14:36  Naturain  阅读(216)  评论(0编辑  收藏  举报