寒假Day16Dinic模板更新+优化

之前的模板好像比较简单,而且没进行cur优化,可能一些大数据过不去,并且建边也会有问题

貌似之前的Dinic模板适用范围有局限性

tot初始化为-1

 

Dinic模板:(邻接表add建边+dfs+bfs)

 1 struct node
 2 {
 3     // int u,v,flow;
 4     int nextt,v,flow;
 5 } e[N*N];
 6 
 7 void add(int u,int v,int flow)
 8 {
 9     tot++;
10     //nextt[tot]=head[u];
11     e[tot].nextt=head[u];
12     head[u]=tot;
13     // e[tot].u=u;
14     e[tot].v=v;
15     e[tot].flow=flow;
16 
17     tot++;
18     // nextt[tot]=head[v];
19     e[tot].nextt=head[v];
20     head[v]=tot;
21     //e[tot].u=v;
22     e[tot].v=u;
23     e[tot].flow=0;
24 }
25 
26 int dfs(int u,int flow)
27 {
28     if(u==t)
29         return flow;
30     for(int &i=cur[u]; i!=-1; i=e[i].nextt) //注意这里的&符号,这样i增加的同时也能改变cur[u]的值,达到记录当前弧的目的
31     {
32         if((dep[e[i].v]==dep[u]+1)&&e[i].flow>0)
33         {
34             int di=dfs(e[i].v,min(flow,e[i].flow));
35             if(di>0)
36             {
37                 e[i].flow-=di;
38                 e[i^1].flow+=di;
39                 return di;
40             }
41         }
42     }
43     return -1;
44 }
45 
46 bool bfs()
47 {
48     if(s==t)return 0;
49     queue<int>Q;
50     while(!Q.empty())
51         Q.pop();
52     memset(dep,-1,sizeof(dep));
53     dep[s]=1;
54     Q.push(s);
55     while(!Q.empty())
56     {
57         int u=Q.front();
58         Q.pop();
59         for (int i=head[u]; i!=-1; i=e[i].nextt)
60         {
61             if ((e[i].flow>0)&&(dep[e[i].v]==-1))
62             {
63                 dep[e[i].v]=dep[u]+1;
64                 Q.push(e[i].v);
65             }
66         }
67     }
68     if(dep[t]!=-1)
69         return 1;
70     return 0;
71 }
72 
73 int dinic()
74 {
75     int sum=0;
76     while(bfs())
77     {
78         for(int i=s; i<=t; i++)
79             cur[i]=head[i];
80         int di;
81         while((di=dfs(s,inf))!=-1)
82             sum+=di;
83     }
84     return sum;
85 }
View Code
原文地址:https://www.cnblogs.com/OFSHK/p/12247272.html