http://acm.hdu.edu.cn/showproblem.php?pid=1532
题意:
从1开始到终点n,最多能通过多少的流量,就比如说1到2的流量是20,2到3的流量是10,那么到达终点3的流量为10,而
1到2还能经过10的流量,2到3不能再通过。
坑爹:
每次找到一条增广轨的时候要补一个反向的边,不然你走这一条路就认为你一定走了,因为有可能这条路不是最佳的路径。
解法:
利用BFS搜索点,找到终点就返回1,没有则返回0,再设置一个maxflow函数,只要BFS的返回值为1,就将这条增广轨上的
最大可以通过的流量(min)算出来(利用change_map函数),然后 max_flow += min。
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 const int maxn = 200 + 10; 5 const int INF = 0x3fffffff; 6 7 int map[maxn][maxn]; 8 int front[maxn]; 9 int used[maxn]; 10 int max_flow; 11 int m; 12 int n; 13 14 void init() 15 { 16 max_flow = 0; 17 memset(map,0,sizeof(map)); 18 } 19 20 int BFS() 21 { 22 memset(used,0,sizeof(used)); 23 queue<int> Q; 24 while(!Q.empty()) 25 { 26 Q.pop(); 27 } 28 Q.push(1); 29 front[1] = 1; 30 used[1] = 1; 31 while(!Q.empty()) 32 { 33 int i; 34 int temp = Q.front(); 35 Q.pop(); 36 for(i=2; i<=n; i++) 37 { 38 if(map[temp][i] != 0 && used[i] == 0) 39 { 40 Q.push(i); 41 used[i] = 1; 42 front[i] = temp; 43 if(i == n) 44 { 45 return 1; 46 } 47 } 48 } 49 } 50 return 0; 51 } 52 53 int change_map() 54 { 55 int min = INF; 56 int temp = n; 57 while(front[temp] != temp) 58 { 59 if(min > map[front[temp]][temp]) 60 { 61 min = map[front[temp]][temp]; 62 } 63 temp = front[temp]; 64 } 65 temp = n; 66 while(front[temp] != temp) 67 { 68 map[front[temp]][temp] -= min; 69 map[temp][front[temp]] += min;//必须补反边 70 temp = front[temp]; 71 } 72 return min; 73 } 74 75 void maxflow() 76 { 77 while(BFS()) 78 { 79 max_flow += change_map(); 80 } 81 } 82 83 int main() 84 { 85 while(cin>>m>>n) 86 { 87 init(); 88 int i; 89 int a; 90 int b; 91 int c; 92 for(i=0; i<m; i++) 93 { 94 cin>>a>>b>>c; 95 map[a][b] += c; 96 } 97 maxflow(); 98 cout<<max_flow<<endl; 99 } 100 return 0; 101 }