版本比较
题解:P4722 【模板】最大流 加强版 / 预流推进
正文
增加 16 行删除 16 行
11 行未改动1213141516161718192065 行未改动868788899090919293944 行未改动9910010110210310410310410510610710833 行未改动14214314414514614614714814915017 行未改动1681691701711721721731741751762 行未改动17918018118218318318418518618715 行未改动20320420520620720720820921021113 行未改动22522622722822922923023123223323423523423523623723823924024124224324424324424524624724810 行未改动25926026126226326326426526626727 行未改动29529629729829929930030130230328 行未改动33233333433533633633733833934021 行未改动11 行未改动
**注意,当前弧优化其实对于 Dinic 不是优化,而是保证 $O(n^2m)$ 时间复杂度的一部分**。
```cpp//Dinic 算法 //Dinic 算法#include<bits/stdc++.h>using namespace std;#define int long longint n,m,s,t;65 行未改动这样时间复杂度能大大降低。
看代码。```cpp//Dinic 算法 //Dinic 算法#include<bits/stdc++.h>using namespace std;#define int long longint n,m,s,t;4 行未改动 head[u]=tot;}int maxflow,dis[10010],now[10010];bool vis[10010];bool bfs(){//BFS 分层 queue<int>q;//STL 队列 bool bfs(){//BFS 分层 queue<int>q;//STL 队列 memset(vis,0,sizeof vis); vis[s]=1,dis[s]=0,now[s]=head[s]; q.push(s); while(!q.empty()){33 行未改动 int p=(1<<i); for(int j=1;j<=m;j++) if(e[j].w>=p && e[j].w<p*2) add(e[j].u,e[j].v,e[j].w),add(e[j].v,e[j].u,0);//枚举边并加入,注意反向边 int flow=0;//跑 Dinic 并统计答案 while(bfs()) while(flow=dinic(s,1e18)) maxflow+=flow;//不删边,留到下一组接着跑 } } cout<<maxflow; return 0;}```17 行未改动发现效率大大提升。
代码。```cpp//Dinic 算法 //Dinic 算法#include<bits/stdc++.h>using namespace std;#define int long longint n,m,s,t;2 行未改动void add(int u,int v,int w){//注意 add 函数有变化 to[++tot]=v,val[tot]=w; nxt[tot]=head[u]; head[u]=tot; e[u].push_back(tot);//这里存的是要去跑 Dinic 的边 e[u].push_back(tot);//这里存的是要去跑 Dinic 的边 to[++tot]=u,val[tot]=0; nxt[tot]=head[v]; head[v]=tot;//反向边先不参与 Dinic,但参与更新}15 行未改动 Q[++T]=to[e[u][i]]; if(to[e[u][i]]==t) return 1; } } return 0; return 0;}int dinic(int x,int flow){ if(x==t) return flow; int rest=flow;13 行未改动signed main() { ios::sync_with_stdio(0); cin>>n>>m>>s>>t; for(int i=1;i<=m;i++) cin>>E[i].u>>E[i].v>>E[i].w; for(int i=30;i>=0;i--){//下面与上面很不一样 for(int i=30;i>=0;i--){//下面与上面很不一样 int p=(1<<i); int kt=tot; for(int j=1;j<=m;j++) if(E[j].w>=p && E[j].w<p*2) add(E[j].u,E[j].v,E[j].w);//存边 int flow=0;//跑 Dinic add(E[j].u,E[j].v,E[j].w);//存边 int flow=0;//跑 Dinic while(bfs()) while(flow=dinic(s,1e18)) maxflow+=flow; for(int j=1;j<=m;j++){//加反向边 if(E[j].w>=p && E[j].w<p*2){ kt+=2; e[E[j].v].push_back(kt); } } while(bfs()) while(flow=dinic(s,1e18)) maxflow+=flow;//再跑一次 } while(bfs()) while(flow=dinic(s,1e18)) maxflow+=flow;//再跑一次 } cout<<maxflow; return 0;}```10 行未改动反正这样是过了。
代码。```cpp//Dinic 算法 //Dinic 算法#include<bits/stdc++.h>using namespace std;#define int long longint n,m,s,t;27 行未改动 Q[++T]=to[e[u][i]]; if(to[e[u][i]]==t) return 1; } } return 0; return 0;}int dinic(int x,int flow){ if(x==t) return flow; int rest=flow;28 行未改动 e[E[j].v].push_back(kt); } } while(bfs()) while(flow=dinic(s,1e18)) maxflow+=flow; } } cout<<maxflow; return 0;}```21 行未改动