[USACO4.2]草地排水Drainage Ditches--最大流--EK

Luogu 2740

[USACO4.2]草地排水Drainage Ditches--最大流--EK

Code:

#include <bits/stdc++.h>
using namespace std;
#define maxn 210
#define maxm 210
const int inf=1<<30;
int n,m,s,t,head[maxm],size=1,vis[maxm];
struct egde {
	int v,w,nxt;
}e[maxn<<1];
struct node {
	int vi,eg;
}pre[maxn<<1];

inline void init_() {
	freopen("a.txt","r",stdin);
}

inline int read_() {
	int x=0,f=1;
	char c=getchar();
	while(c<'0'||c>'9') {
		if(c=='-') f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9') {
		x=(x<<3)+(x<<1)+c-'0';
		c=getchar();
	}
	return x*f;
}

inline void add_(int u,int v,int w) {
	e[++size].v=v;
	e[size].w=w;
	e[size].nxt=head[u];
	head[u]=size;
}

inline void clean_() {
	memset(head,-1,sizeof(head));
}

bool bfs_() {
	memset(vis,0,sizeof(vis));
	memset(pre,-1,sizeof(pre));
	queue<int >q;
	q.push(s);
	vis[s]=1;
	while(!q.empty()) {
		int u=q.front();
		q.pop();
		for(int i=head[u];~i;i=e[i].nxt) {
			int v=e[i].v,w=e[i].w;
			if(!vis[v]&&w) {
				pre[v].vi=u;
				pre[v].eg=i;
				if(v==t) return 1;
				vis[v]=1;
				q.push(v);
			}
		}
	}
	return 0;
}

int EK_() {
	int ans=0;
	while(bfs_()) {
		int mi=inf;
		for(int i=t;i!=s;i=pre[i].vi) {
			mi=min(mi,e[pre[i].eg].w);
		}
		for(int i=t;i!=s;i=pre[i].vi) {
			e[pre[i].eg].w-=mi;
			e[pre[i].eg^1].w+=mi;
		}
		ans+=mi;
	}	
	return ans;
}

void readda_() {
	clean_();
	n=read_();m=read_();s=1;t=m;
	int a,b,c;
	for(int i=1;i<=n;++i) {
		a=read_();b=read_();c=read_();
		add_(a,b,c);add_(b,a,0);
	}
	printf("%d",EK_());
}

int main() {
	init_();
	readda_();
	return 0;
}
上一篇:网络流EK


下一篇:Drainage Ditches HDU 1532 (网络流 最大流 EK模板)