POJ--1087(最大流)

本文介绍了一种解决插座转换器问题的最大流算法实现。通过构造一个包含源点、汇点及中间点的图,并设置相应的容量限制,利用Dinic算法求解最大流,进而得出所需的转换器数量。

2014-12-20 15:58:19

思路:考了一发建图....其实也比较简单,首先定一个总源点和一个总汇点,然后根据拥有的插座建立中间点到汇点的通道,容量为1,根据需求建立源点到中间点的通道,容量为某种插座的需求量。对于转换器,在中间点之间建立容量为INF的通道即可。

  (others:当然这题这种建图可以完全倒过来,相当于从总汇点倒流到总源点,那么就要把总汇/源点互换,转换器的建的边反一下。)

 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 = 410;
21 
22 int n,m,k,tot;
23 string s[maxn];
24 map<string,int> mp;
25 int c[maxn][maxn],lev[maxn];
26 int Q[maxn],head,rear;
27 
28 void Bfs(){
29     memset(lev,-1,sizeof(lev));
30     lev[0] = 0;
31     Q[head = rear = 1] = 0;
32     while(head <= rear){
33         int x = Q[head++];
34         for(int i = 1; i <= tot; ++i) if(c[x][i] > 0 && lev[i] < 0){
35             lev[i] = lev[x] + 1;
36             Q[++rear] = i;
37         }
38     }
39 }
40 
41 int Dfs(int p,int minf){
42     if(p == tot) return minf;
43     for(int i = 1; i <= tot; ++i) if(lev[i] > lev[p] && c[p][i] > 0){
44         int d = Dfs(i,min(minf,c[p][i]));
45         if(d > 0){
46             c[p][i] -= d;
47             c[i][p] += d;
48             return d;
49         }
50     }
51     return 0;
52 }
53 
54 int Dinic(){
55     int max_flow = 0,plus;
56     while(1){
57         Bfs();
58         if(lev[tot] < 0) break;
59         while((plus = Dfs(0,INF)) > 0) max_flow += plus;
60     }
61     return max_flow;
62 }
63 
64 int main(){
65     memset(c,0,sizeof(c));
66     tot = 0;
67     string t1,t2;
68     scanf("%d",&n);
69     for(int i = 1; i <= n; ++i){
70         cin >> s[i];
71         mp[s[i]] = ++tot;
72     }
73     scanf("%d",&m);
74     for(int i = 1; i <= m; ++i){
75         cin >> t1 >> t2;
76         if(mp.find(t2) == mp.end()) mp[t2] = ++tot;
77         c[0][mp[t2]]++;
78     }
79     scanf("%d",&k);
80     for(int i = 1; i <= k; ++i){
81         cin >> t1 >> t2;
82         if(mp.find(t1) == mp.end()) mp[t1] = ++tot;
83         if(mp.find(t2) == mp.end()) mp[t2] = ++tot;
84         c[mp[t1]][mp[t2]] = INF;
85     }
86     ++tot;
87     for(int i = 1; i <= n; ++i)
88         c[mp[s[i]]][tot] = 1;
89     printf("%d\n",m - Dinic());
90     return 0;
91 }

 

转载于:https://www.cnblogs.com/naturepengchen/articles/4175524.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值