POJ 2135 Farm Tour (最小费用最大流)
两遍spfa解决
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int maxn=30000;
const int inf=2000000000;
struct edge{
int u,v,next,f,c;
edge(int u0=0,int v0=0,int f0=0,int c0=0,int next0=0){
u=u0,v=v0,f=f0,c=c0,next=next0;
}
}e[maxn*10];
int head[maxn*2],visited[maxn*2],path[maxn*2],dist[maxn*2];
int cnt,from,to,marked,n,r,m;
void initial(){
cnt=0;marked=1;
from=1;to=n;
for(int i=0;i<=n;i++){
head[i]=-1;
visited[i]=0;
}
}
void adde(int u,int v,int f,int c){
e[cnt].u=u,e[cnt].v=v,e[cnt].f=f,e[cnt].c=c,e[cnt].next=head[u],head[u]=cnt++;
e[cnt].u=v,e[cnt].v=u,e[cnt].f=0,e[cnt].c=-c,e[cnt].next=head[v],head[v]=cnt++;
}
void input(){
int u0,v0,c0;
while(m-- >0){
scanf("%d%d%d",&u0,&v0,&c0);
adde(u0,v0,1,c0);
adde(v0,u0,1,c0);
}
}
void bfs(){
for(int i=0;i<=n;i++){
dist[i]=inf;
path[i]=-1;
}
dist[from]=0;
queue <int> q;
q.push(from);
marked++;
visited[from]=marked;
while(!q.empty()){
int s=q.front();
q.pop();
for(int i=head[s];i!=-1;i=e[i].next){
int d=e[i].v;
if(e[i].f>0 && dist[s]+e[i].c<dist[d]){
dist[d]=dist[s]+e[i].c;
path[d]=i;
if(visited[d]!=marked){
visited[d]=marked;
q.push(d);
}
}
}
visited[s]=-1;
}
}
void computing(){
int k=2,ans=0;
while(k-- >0){
bfs();
ans+=dist[to];
for(int i=to;i!=from;i=e[path[i]].u){
e[path[i]].f-=1;
e[path[i]^1].f+=1;
}
}
cout<<ans<<endl;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
initial();
input();
computing();
}
return 0;
}