Day66:HDU3549- Flow Problem-最大流模板题-EK算法

求最大流模板题

用了EK算法,即bfs+max_flow

具体解析可以看我这篇博客https://www.cnblogs.com/OFSHK/p/12231765.html#_label3

AC代码:

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<queue>
 4 #include<string.h>
 5 using namespace std;
 6 #define inf 0x3f3f3f3f
 7 
 8 const int N=20;
 9 int e[N][N],s,t,m,n,pre[N];
10 bool book[N];
11 
12 bool bfs()
13 {
14 //    memset(book,0,sizeof(book));
15 //    memset(pre,0,sizeof(pre));
16     for(int i=0;i<=t;i++)
17         book[i]=pre[i]=0;
18     queue<int>Q;
19     Q.push(s);
20     book[s]=1;
21     while(!Q.empty())
22     {
23         int u=Q.front();
24         Q.pop();
25         if(u==t)
26             return 1;
27         for(int i=1; i<=n; i++)
28         {
29             if(book[i]==0)
30             {
31                 if(e[u][i])
32                 {
33                     book[i]=1;
34                     pre[i]=u;
35                     Q.push(i);
36                 }
37             }
38         }
39     }
40     return 0;
41 }
42 
43 int max_flow()
44 {
45     int maxflow=0;
46     while(bfs())
47     {
48 //        if(bfs()==0)
49 //            return maxflow;
50         int minn=inf;
51         for(int i=t; i!=s; i=pre[i])
52             minn=min(minn,e[pre[i]][i]);
53         for(int i=t; i!=s; i=pre[i])
54         {
55             e[pre[i]][i]-=minn;
56             e[i][pre[i]]+=minn;
57         }
58         maxflow+=minn;
59     }
60     return maxflow;
61 }
62 
63 int main()
64 {
65     int u,v,w,tt=1,T;
66     scanf("%d",&T);
67     while(T--)
68     {
69         scanf("%d %d",&n,&m);
70         memset(e,0,sizeof(e));
71         s=1,t=n;
72         for(int i=1; i<=m; i++)
73         {
74             int u,v,w;
75             scanf("%d %d %d",&u,&v,&w);
76             e[u][v]+=w;
77         }
78         int ans=max_flow();
79         printf("Case %d: %d\n",tt++,ans);
80     }
81     return 0;
82 }
View Code

猜你喜欢

转载自www.cnblogs.com/OFSHK/p/12655794.html