今天首次接触到网络流,看了半天有些地方还是不太理解,关于算法本身的理解可能还有点问题,所以在实现上还有点困难
1 #include <cstdio> 2 #include <cstring> 3 #define Max 0x7f7f7f7f 4 int n,m; 5 int path[205][205]; 6 int visited[205]; 7 int que[205]; 8 int pre[205]; 9 int flow[205]; 10 int min(int a ,int b) 11 { 12 return a>b?b:a; 13 } 14 int BFS()//查找有没有增广路 15 { 16 memset(visited,0,sizeof(visited)); 17 memset(pre,-1,sizeof(pre)); 18 memset(flow,Max,sizeof(flow)); 19 int head=0; 20 int tail=1; 21 que[head]=1; 22 visited[1]=1; 23 while(head<tail) 24 { 25 int tmp=que[head]; 26 if(tmp==m) break; 27 for(int i=2;i<=m;i++) 28 { 29 if(visited[i]==0 && path[tmp][i]!=0) 30 { 31 visited[i]=1; 32 pre[i]=tmp; 33 que[tail]=i; 34 flow[i]=min(flow[tmp],path[tmp][i]); 35 tail++; 36 37 } 38 } 39 head++; 40 } 41 if(visited[m]==0) 42 return -1; 43 else return flow[m];//有增广路 44 } 45 46 int Ford_Fulkerson() 47 { 48 int nowflow,maxflow=0; 49 while((nowflow=BFS())!=-1)//更新残余网络 50 { 51 maxflow+=nowflow; 52 int tmp=m; 53 while(tmp!=1) 54 { 55 int before=pre[tmp]; 56 path[before][tmp]-=nowflow; 57 path[tmp][before]+=nowflow; 58 tmp=before; 59 } 60 } 61 return maxflow; 62 } 63 64 int main() 65 { 66 int start,end,value; 67 while(scanf("%d%d",&n,&m)!=EOF) 68 { 69 memset(path,0,sizeof(path)); 70 for(int i=1;i<=n;i++) 71 { 72 scanf("%d%d%d",&start,&end,&value); 73 path[start][end]+=value; 74 } 75 printf("%d\n",Ford_Fulkerson()); 76 } 77 78 return 0; 79 }
更正下,上面的算法不叫Ford_Fulkerson ,而是EK
下面这几个链接可以参考下: