您的位置:首页 > 其它

uva820 Internet Bandwidth(最大流模板题)

2015-08-24 23:40 399 查看
套的Dinic模板,权当测模板了~

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<vector>
#include<iostream>
#define PB push_back
#define POB pop_back
#define PII pair<int, int>
#define PDD pair<double, double>
#define rep(i, a, b) for(int i = a ; i < b ; i++)
#pragma comment(linker, "/STACK:1024000000,1024000000")
#pragma GCC push_options
#pragma GCC optimize ("Os")
#pragma  loop_opt(on)
#ifdef WIN32
#define INT64 "%I64d"
#define UINT64 "%I64u"
#else
#define INT64 "%lld"
#define UINT64 "%llu"
#endif
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 110;
struct Edge {
int from, to, cap, flow;
Edge(int from, int to, int cap, int flow) : from(from), to(to), cap(cap), flow(flow) {}
};
struct Dinic {
int n, m, s, t;
vector<Edge> edges;
vector<int> G[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void AddEdge(int from, int to, int cap) {
edges.PB(Edge(from, to, cap, 0));
edges.PB(Edge(from, to, 0, 0));
m = edges.size();
G[from].PB(m - 2);
G[to].PB(m - 1);
}

bool BFS() {
memset(vis, 0, sizeof vis);
queue<int> Q;
Q.push(s);
d[s] = 0;
vis[s] = 1;
while(!Q.empty()) {
int x = Q.front(); Q.pop();
for(int i = 0 ; i < (int)G[x].size() ; 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 <(int)G[x].size() ; 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;
}

void init() {
edges.clear();
for(int i = 0 ; i < maxn ; i++) G[i].clear();
memset(d, 0, sizeof d);
}
} dinic;
int main()
{
int n;
int ca = 1;
while(scanf("%d", &n) == 1 && n) {
dinic.init();
int a, b, m; scanf("%d%d%d" ,&a,  &b, &m);
int from, to, cap;
for(int i = 0 ; i < m ; i++) scanf("%d%d%d", &from, &to, &cap), dinic.AddEdge(from, to, cap), dinic.AddEdge(to, from, cap);
printf("Network %d\n", ca++);
printf("The bandwidth is %d.\n\n", dinic.MaxFlow(a, b));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: