您的位置:首页 > 其它

hdu1532 当前弧优化的dinic算法实现

2016-07-28 19:59 381 查看
点击打开链接

裸题,主要练习手速!

#include <queue>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int max_node = 205;
const int INF = 0x3f3f3f3f;
struct Edge{
int to,cap,rev;
Edge(int t,int c,int r):to(t), cap(c), rev(r) {}
};
vector<Edge> G[max_node];
int edge_num,sink;
int cur[max_node];
int dis[max_node];

void push_edge(int from,int to,int cap){
G[from].push_back( Edge(to,cap,G[to].size()));
G[to].push_back( Edge(from,0,G[from].size()-1));
}

void bfs(){
memset(dis,-1,sizeof(dis));
queue<int> q;
q.push(1);
dis[1]=0;
while(!q.empty()){
int t = q.front(); q.pop();
for(int i = 0; i < G[t].size(); i++){
Edge &e = G[t][i];
if(e.cap > 0 && dis[e.to] == -1){
dis[e.to] = dis[t] + 1;
q.push(e.to);
}
}
}
}

int dfs(int u,int v,int res){
if(u == v) return res;
for(int i = cur[u]; i< G[u].size(); i++){
Edge &e = G[u][i];
if(e.cap > 0 && dis[e.to] == dis[u] + 1){
int x = dfs(e.to, v, min(res, e.cap));
if(x > 0){
e.cap -= x;
G[e.to][e.rev].cap += x;
cur[u] = i;
return x;
}
}
}
return 0;
}
int max_flow(){
int flow = 0;
while(1){
memset(cur, 0, sizeof(cur));
bfs();
if(dis[sink] == -1){
return flow;
}
while(int x = dfs(1,sink,INF)){
flow += x;
}
}
}

int main(){
#ifdef LOCAL_DEBUG
freopen("input.txt" ,"r" ,stdin);
#endif // LOCAL_DEBUG
while(scanf("%d%d" ,&edge_num, &sink)!=EOF){
for(int i=0; i < max_node; i++) G[i].clear();
int from,to,cap;
for(int i=1; i<=edge_num; i++){
scanf("%d%d%d" ,&from, &to, &cap);
push_edge(from,to,cap);
}
printf("%d\n" ,max_flow());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: