您的位置:首页 > 大数据 > 人工智能

POJ 1273.Drainage Ditches【最大流】

2010-07-26 01:32 351 查看
不用多说了,赤裸裸的最大流,典型的模板题。dinic算法实现。

#include <cstdio>
#include <cstring>
#include <list>
#include <queue>
#define INF 0x1f1f1f1f
#define MAXN 205
using namespace std;
int n,m,src,sink;       //点数,边数,源点,汇点
int restflow[MAXN][MAXN],level[MAXN]; //层次值
bool flag[MAXN];
inline void initial(){
int st,ed,w;
memset(restflow,0,sizeof(restflow));
src = 1; sink = n;
for(int i = 1;i <= m; ++i){
scanf("%d%d%d",&st,&ed,&w);
restflow[st][ed] += w;
}
}
inline int hasflow(int x){
for(int i = 1;i <= n; ++i)
if(restflow[x][i] && level[x] + 1 == level[i])
return i;
return 0;
}
inline bool BFS(){
bool mark = false;
queue<int>que;
while(!que.empty()) que.pop();
memset(flag,false,sizeof(flag));
memset(level,1,sizeof(level));
que.push(src);         //源点入队
flag[src] = true;
level[src] = 0;
while(!que.empty()){
int tep = que.front();
que.pop();
for(int i = 1;i <= n; ++i){
if(!flag[i] && restflow[tep][i] != 0){
flag[i] = true;
level[i] = level[tep] + 1;
que.push(i);
}
}
if(tep == sink) mark = true;
}
return mark;
}
inline int dinic(){
int u,v,capflow,last,maxflow = 0;
list<int>path;
list<int>::iterator its;
while(BFS()){
path.clear();
path.push_back(src);
while(hasflow(src)){
u = path.back();
if(u != sink){
if(v = hasflow(u))
path.push_back(v);
else{
path.pop_back();
level[u] = INF;
}
}
else{
capflow = INF;
for(its = path.begin(); its != path.end(); ++its){
u = *its;
if((++its) == path.end()) break;
v = *its;
if(restflow[u][v] < capflow)
capflow = restflow[u][v];
--its;
}
last = -1;
maxflow += capflow;
for(its = path.begin(); its != path.end(); ++its){
u = *its;
if((++its) == path.end()) break;
v = *its;
restflow[u][v] -= capflow;
restflow[v][u] += capflow;
if(restflow[u][v] == 0 && last == -1)
last = u;
--its;
}
while(path.back() != last) path.pop_back();
}
}
}
return maxflow;
}
int main()
{
while(scanf("%d%d",&m,&n) != EOF){
initial();
printf("%d/n",dinic());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: