您的位置:首页 > 其它

HDU1532 最大流-模板题

2013-02-09 08:05 393 查看
题目是网络流-最大流的模板题
这里作为学习,把《指南》上Dinic的模板用了一下,代码如下:

#include <stdio.h>
#include <iostream>
#include <queue>
#include <string.h>
#include <vector>
using namespace std;
const int MAXN = 10000;
const int INF = 0x3f3f3f3f;
int min(int a, int b){
return a
}
struct Edge{
int from, to, cap, flow;
Edge(int a, int b, int c, int d): from(a), to(b), cap(c), flow(d) {}
};

struct Dinic {
int n, m, s, t;
vector edges;
vectorG[MAXN];
bool vis[MAXN];
int d[MAXN];
int cur[MAXN];

void AddEdge(){
int from, to, cap;
scanf("%d%d%d", &from, &to, &cap);
Edge tedge = Edge(from, to, cap, 0);
edges.push_back(tedge);
tedge = Edge(to, from, 0, 0);
edges.push_back(tedge);
int m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}

bool BFS() {
memset(vis, 0, sizeof(vis));
queueq;
q.push(s);
d[s] = 0;
vis[s] = 1;
while(!q.empty()){
int x = q.front();
q.pop();
for(int i=0; i
Edge &e = edges[G[x][i]];
if(!vis[e.to] && e.cap > e.flow){
vis[e.to] = 1;
d[e.to] = d[x] + 1;
q.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x, int a){
if(x==t || a==0) return a;
int flow = 0, f;
for(int& i=cur[x]; i
Edge& e = edges[G[x][i]];
if(d[x]+1==d[e.to] && (f=DFS(e.to, min(a, e.cap-e.flow))) > 0) {
e.flow += f;
edges[G[x][i]^1].flow -= f;
flow += f;
a -= f;
if(a==0) break;
}
}
return flow;
}
int Maxflow(int s, int t){
this->s = s;
this->t = t;
int flow = 0;
while(BFS()) {
memset(cur, 0, sizeof(cur));
flow += DFS(s, INF);
}
return flow;
}
};
int main(){
// freopen("in.txt", "r", stdin);
int n, m;
while(scanf("%d%d", &n, &m)!=EOF){
int i;
Dinic din;
for(i=0; i
din.AddEdge();
}
printf("%d\n", din.Maxflow(1, m));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: