PAT顶级 1003 Universal Travel Sites (35分)(最大流)

题目链接:

1003 Universal Travel Sites (35分)

思路:

题目问stationstation的最小容量,变相就是问最多能一次性出发多少人,使得过程中不会超过每条边的容量,即最大流问题,用FordFulkersonFord-Fulkerson算法可很快地解决;

代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int maxn=1005;
const int INF=1<<30;
struct edge{int to,cap,rev;};
vector<edge> G[maxn];
bool used[maxn];
void add_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});
}
int dfs(int v,int t,int f){
	if(v==t) return f;
	used[v]=true;
	for(edge& e:G[v])
		if(!used[e.to]&&e.cap>0){
			int d=dfs(e.to,t,min(f,e.cap));
			if(d>0){
				e.cap-=d;
				G[e.to][e.rev].cap+=d;
				return d;
			}
		}
	return 0;
}
int max_flow(int s,int t){
	int flow=0;
	while(true){
		memset(used,0,sizeof(used));
		int f=dfs(s,t,INF);
		if(f==0) return flow;
		flow+=f;
	}
}
int main(){
//	freopen("Sakura.txt","r",stdin);
	int n,cnt=2;
	map<string,int> mp;
	string s1,s2; cin>>s1>>s2>>n;
	mp[s1]=1; mp[s2]=2;
	for(int i=0;i<n;i++){
		int cap,from,to;
		cin>>s1>>s2>>cap;
		if(mp[s1]) from=mp[s1]; else mp[s1]=from=++cnt;
		if(mp[s2]) to=mp[s2]; else mp[s2]=to=++cnt;
		add_edge(from,to,cap);
	}
	cout<<max_flow(1,2);
	return 0;
}
原文地址:https://www.cnblogs.com/yuhan-blog/p/12308740.html