最大流Dinic
2024-10-18 21:20:48
不断用BFS构造分层网络,用DFS增广。中途用取指的cur优化DFS。
Dinic封装模板:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
typedef long long L;
const int maxn = + ;
const int maxm = + ;
const int INF = -1u >> ;
int fch[maxn], n, m;
L ans = ;
bool vis[maxn];
struct Tedge{
int from, to, cap, flow, next;
}adj[maxm];
struct Dinic{
int S, T, n, ms;
int d[maxn], cur[maxn], fch[maxn];
void init(int n){
this -> n = n;
memset(fch, -, sizeof(fch));
ms = ;
return ;
}
void AddEdge(int u, int v, int c){
adj[ms] = (Tedge){u, v, c, , fch[u]};
fch[u] = ms ++;
adj[ms] = (Tedge){v, u, , , fch[v]};
fch[v] = ms ++;
return ;
}
bool BFS(){
memset(vis, , sizeof(vis));
queue<int> Q;
Q.push(S); vis[S] = true; d[S] = ;
while(!Q.empty()){
int x = Q.front(); Q.pop();
for(int i = fch[x]; i != -; i = adj[i].next){
Tedge& e = adj[i];
if(!vis[e.to] && e.cap > e.flow){
vis[e.to] = true;
d[e.to] = d[x] + ;
Q.push(e.to);
}
}
}
return vis[T];
}
int DFS(int x, int a){
if(x == T || !a) return a;
int flow = , f;
for(int& i = cur[x]; i != -; i = adj[i].next){
Tedge& e = adj[i];
if(d[e.to] == d[x] + && (f = DFS(e.to, min(a, e.cap - e.flow))) > ){
flow += f;
a -= f;
e.flow += f;
adj[i ^ ].flow -= f;
if(!a) break;
}
}
return flow;
}
L Max_Flow(int S, int T){
this -> S = S;
this -> T = T;
L flow = ;
while(BFS()){
for(int i = ; i < n; i ++) cur[i] = fch[i];
flow += DFS(S, INF);
}
return flow;
}
}sol;
void read(int &x){
x = ; int sig = ; char ch = getchar();
while(!isdigit(ch)) { if(ch == '-') sig = -; ch = getchar(); }
while(isdigit(ch)) x = * x + ch - '', ch = getchar();
x *= sig; return ;
}
void init(){
read(n); read(m);
sol.init(n);
int u, v, w;
for(int i = ; i < m; i++){
read(u); read(v); read(w);
sol.AddEdge(u, v, w);
}
return ;
}
void work(){
ans = sol.Max_Flow(, n);
return ;
}
void print(){
printf("%lld\n", ans);
return ;
}
int main(){
init();
work();
print();
return ;
}
最新文章
- SQL Server COM 组件创建实例失败
- NSString和NSMutableString的创建及其一些常用方法
- POJ 1363 Rails
- MVC5 + EF6 + Bootstrap3 (11) 排序、搜索、分页
- yum 安装mysql5.6
- cocos2dx中的CCLayerColor
- Tomcat配置HTTPS方式生成安全证书
- Android develop tricks——整理自国外的一些Blog
- UVA 11021 Tribles(递推+概率)
- JVM中内存回收深入分析,各种垃圾收集器
- 搜索表字段包含某字符串的SQL和监控Oracle数据库的SQL。
- 【Mac】-NO.161.Mac.1 -【MacOS 中环境变量设置 zsh: command not found: xxx】
- c#实现文件写入数据表/以二进制流保存到数据库,并实现下载
- RNN入门(4)利用LSTM实现整数加法运算
- Loader监听数据源的变化
- MyBatis 别名标签 &; sql的复用
- zk可视化工具
- excel文件批量重命名
- HDU1540 Tunnel Warfare(线段树区间维护&;求最长连续区间)题解
- mybatis后台中传参到sql语句中,使用@Param注解