題目鏈接: https://nanti.jisuanke.com/t/36
題意:中文題目誒~
思路: 最大流模板題....
關於最大流算法blog:
http://www.cnblogs.com/zsboy/archive/2013/01/27/2878810.html
http://blog.csdn.net/y990041769/article/details/21026445
http://www.cnblogs.com/luweiseu/archive/2012/07/14/2591573.html
代碼:
1 #include <iostream> 2 #include <stdio.h> 3 #include <queue> 4 #include <string.h> 5 using namespace std; 6 7 const int MAXN=2e2+10; 8 const int inf=0x7fffffff; 9 int capacity[MAXN][MAXN];//記錄殘留網絡流量 10 int flow[MAXN]; //標記從源點到當前節點實際還剩多少流量可用 11 int pre[MAXN]; //pre[i]爲i的父親節點 12 int n, m; 13 14 int bfs(int src, int des){ 15 queue<int> q; 16 while(!q.empty()){ 17 q.pop(); 18 } 19 for(int i=1; i<=m; i++){ 20 pre[i]=-1; 21 } 22 pre[src]=0; 23 flow[src]=inf; 24 q.push(src); 25 while(!q.empty()){ 26 int indx=q.front(); 27 q.pop(); 28 if(indx==des) break;//找到了增廣徑 29 for(int i=1; i<=m; i++){ 30 if(i!=src&&capacity[indx][i]>0&&pre[i]==-1){ 31 pre[i]=indx; 32 flow[i]=min(capacity[indx][i], flow[indx]); 33 q.push(i); 34 } 35 } 36 } 37 if(pre[des]==-1) return -1; 38 return flow[des]; 39 } 40 41 int edmond_karp(int src, int des){ 42 int increasement=0; 43 int sumflow=0; 44 while((increasement=bfs(src, des))!=-1){ 45 int k=des; //利用前區尋找路徑 46 while(k!=src){ 47 int last=pre[k]; 48 capacity[last][k]-=increasement;//改變正向邊容量 49 capacity[k][last]+=increasement;//改變反向邊容量 50 k=last; 51 } 52 sumflow+=increasement; 53 } 54 return sumflow; 55 } 56 57 int main(void){ 58 int start, end, ci; 59 while(~scanf("%d%d", &n, &m)){ 60 memset(capacity, 0, sizeof(capacity)); 61 memset(flow, 0, sizeof(flow)); 62 for(int i=0; i<n; i++){ 63 scanf("%d%d%d", &start, &end, &ci); 64 if(start==end) continue; 65 capacity[start][end]+=ci;//可能有重邊 66 } 67 printf("%d\n", edmond_karp(1, m)); 68 } 69 return 0; 70 }
时间: 2024-10-10 13:05:30