最大流算法 Dinic算法 ADT

https://www.cnblogs.com/SYCstudio/p/7260613.html

这个博主写的很好完全看得懂就不自己写了

方便自己使用还是把模板抄出来吧。

ADT:

 1 const int max_e = 55000;
 2 const int max_v = 250;
 3 const int INF = 0x3f3f3f3f; //可能有时候要用Long Long
 4 
 5 struct Edge{
 6     int from,to,cap;  //很多时候要用long long int cap,因为可能不够
 7     int next; //也可以用vector来存 从from出来的下一条边
 8 }edges[max_e];
 9 int head[max_v]; //第一个从这个点出来的边对应的序号
10 int cnt; //边的数量
11 int Depth[max_v];
12 int f[max_e];
13 int S,T;
14 
15 void init(){
16     cnt = 0;
17     memset(head,-1,sizeof(head));
18     memset(f,0,sizeof(f));
19 }
20 
21 void AddEdge(int f, int t, int cap){
22     edges[cnt].from = f;
23     edges[cnt].to = t;
24     edges[cnt].cap = cap;
25     edges[cnt].next = head[f];
26     head[f] = cnt;
27     cnt++;
28     //??????????
29     edges[cnt].from = t;
30     edges[cnt].to = f;
31     edges[cnt].cap = 0; //反向边
32     edges[cnt].next = head[t];
33     head[t] = cnt;
34     cnt++;
35     
36 }
37 
38 bool bfs(){
39     queue<int>Q;
40     while(!Q.empty()) Q.pop();
41     memset(Depth,0,sizeof(Depth));
42     Depth[S] = 1;
43     Q.push(S);
44     while(!Q.empty()){
45         int u = Q.front();
46         Q.pop();
47         for(int i=head[u];i!=-1;i=edges[i].next){
48             int t = edges[i].to;
49             if((Depth[t]==0)&&edges[i].cap>f[i]){
50                 Depth[t] = Depth[u] + 1;
51                 Q.push(t);
52             }
53         }
54     }
55     if(Depth[T]>0){
56         return 1;
57     }
58     return 0;
59 }
60 
61 int dfs(int u, int dist){ //当前节点,当前流量
62     if(u==T) return dist;
63     for(int i=head[u];i!=-1&&dist;i=edges[i].next){
64         int t = edges[i].to;
65         if(Depth[t]==(Depth[u]+1)&&edges[i].cap>f[i]){
66             int di = dfs(t,min(dist,edges[i].cap-f[i]));
67             if(di>0){//增广成功
68                 f[i] += di;
69                 f[i^1] -= di;
70                 return di;
71             }
72         }
73     }
74     
75     return 0;
76 }
77 
78 int dinic(){
79     int ans=0;
80     while(bfs()){
81         while(int d=dfs(S,INF)) {
82             ans += d;
83         }
84     }
85     return ans;
86 }
View Code

 

posted @ 2018-03-21 12:57  摇啊摇啊  阅读(139)  评论(0编辑  收藏  举报