【网络流】 POJ 1273 Drainage Ditches

最大流模板题。。。写个模板即可。。。。关于ISAP的资料。ISAP

#include <iostream>
#include <queue> 
#include <stack> 
#include <map> 
#include <set> 
#include <bitset> 
#include <cstdio> 
#include <algorithm> 
#include <cstring> 
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 205
#define maxm 1005
#define eps 1e-10
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
//#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
LL gcd(LL _a, LL _b){if(!_b) return _a;else return gcd(_b, _a%_b);}
// head

struct Edge
{
	int v, next;
	LL c;
	Edge() {}
	Edge(int v, LL c, int next) : v(v), c(c), next(next) {}
}E[maxm];

queue<int> q;
int H[maxn], cntE;
int cur[maxn];
int dis[maxn];
int pre[maxn];
int cnt[maxn];
int s, t, nv;
int n, m;
LL flow;

void addedges(int u, int v, int c)
{
	E[cntE] = Edge(v, c, H[u]);
	H[u] = cntE++;
	E[cntE] = Edge(u, 0, H[v]);
	H[v] = cntE++;
}

void bfs(void)
{
	memset(cnt, 0, sizeof cnt);
	memset(dis, -1, sizeof dis);
	cnt[0] = 1, dis[t] = 0;
	q.push(t);
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		for(int e = H[u]; ~e; e = E[e].next) {
			int v = E[e].v;
			if(dis[v] == -1) {
				dis[v] = dis[u] + 1;
				cnt[dis[v]]++;
				q.push(v);
			}
		}
	}
}

LL isap(void)
{
	memcpy(cur, H, sizeof cur);
	bfs();
	flow = 0;
	int u = pre[s] = s, e, pos, minv;
	LL f;
	while(dis[s] < nv) {
		if(u == t) {
			f = INF;
			for(e = s; e != t; e = E[cur[e]].v) if(f > E[cur[e]].c) {
				f = E[cur[e]].c;
				pos = e;
			}
			for(e = s; e != t; e = E[cur[e]].v) {
				E[cur[e]].c -= f;
				E[cur[e] ^ 1].c += f;
			}
			flow += f;
			u = pos;
		}
		for(e = H[u]; ~e; e = E[e].next) if(E[e].c && dis[E[e].v] + 1 == dis[u]) break;
		if(~e) {
			cur[u] = e;
			pre[E[e].v] = u;
			u = E[e].v;
		}
		else {
			if(--cnt[dis[u]] == 0) break;
			for(minv = nv, e = H[u]; ~e; e = E[e].next) if(E[e].c && minv > dis[E[e].v]) {
				minv = dis[E[e].v];
				cur[u] = e;
			}
			dis[u] = minv + 1;
			cnt[dis[u]]++;
			u = pre[u];
		}
	}
	return flow;
}

void init(void)
{
	cntE = 0;
	memset(H, -1, sizeof H);
}

void read(void)
{
	int u, v, c;
	while(m--) {
		scanf("%d%d%d", &u, &v, &c);
		addedges(u, v, c);
	}
}

void work(void)
{
	s = 1, t = n;
	nv = n;
	printf("%lld\n", isap());
}

int main(void)
{
	while(scanf("%d%d", &m, &n)!=EOF) {
		init();
		read();
		work();
	}

	return 0;
}


你可能感兴趣的:(HDU,网络流)