您的位置:首页 > 其它

POJ 1459.Power Network

2017-10-27 17:22 489 查看
题目:http://poj.org/problem?id=1459

AC代码(C++):

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#include <string.h>
#include <bitset>

#define INF 0xfffffff
#define MAXN 105

using namespace std;

int n,np,nc,m;
int map[MAXN][MAXN];
bool vis[MAXN];
int pre[MAXN];

bool getroute(int s, int e){
int len = n + 2;
int temp;
memset(vis,false,sizeof(vis));
for (int i = 0; i < len; i++)pre[i] = -1;
bool haveroute = false;
queue<int> que;
que.push(s);
vis[s] = true;
while (!haveroute && !que.empty()){
temp = que.front();
que.pop();
for (int i = 0; i < len; i++){
if (map[temp][i] && !vis[i]){
vis[i] = true;
pre[i] = temp;
if (i == e){
haveroute = true;
break;
}
que.push(i);
}
}
}
if (!haveroute)return false;
return true;
}

int getMaxflow(int s, int e){
int t;
int result = 0;
while (getroute(s, e)){
int minflow = INF;
t = e;
while (pre[t] != -1){
minflow = min(minflow, map[pre[t]][t]);
t = pre[t];
}
t = e;
while (pre[t] != -1){
map[pre[t]][t] -= minflow;
map[t][pre[t]] += minflow;
t = pre[t];
}
result += minflow;
}
return result;
}

int main(){
while(cin>>n>>np>>nc>>m){
memset(map,0,sizeof(map));
char tmp;
int u,v,val;
int start = n;
int end = n+1;
for(int i = 0; i < m; i++){
cin>>tmp;
cin>>u;
cin>>tmp;
cin>>v;
cin>>tmp;
cin>>val;
map[u][v] = val;
}
for(int i = 0; i < np; i++){
cin>>tmp;
cin>>v;
cin>>tmp;
cin>>val;
map[start][v]=val;
}
for(int i = 0; i < nc; i++){
cin>>tmp;
cin>>u;
cin>>tmp;
cin>>val;
map[u][end]=val;
}
cout<<getMaxflow(start,end)<<endl;
}
}

总结: 最大网络流问题. 题目是多源的, 可以设置一个真正的起点和终点, 把多个源点看做是真正起点的相邻点, 起点到各源点有一条权值为这个源点提供流量的值的边, 同理各消费点也直接连到终点, 权值为各消费点的最大消费值, 这样就转化为了单源点的网络最大流问题. 然后使用Edmonds-Karp算法解决. (这题目的输入格式很有意思, 以后遇到这样奇葩的格式可以像这样直接cin到char来吸收掉多余的符号)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: