poj 2135
一道基础题,却因为这样那样的粗心,用了这么长时间,和uva10086一模一样
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn=1100;
const int maxe=30000;
const int inf=200000000;
struct Edge
{
int from,to,flow,cap,cost,next;
};
int n,m,tot;
int head[maxn],d[maxn],a[maxn],vis[maxn];
Edge edges[maxe];
void addedge(int from,int to,int cap,int cost)
{
edges[tot].from=from;edges[tot].to=to;edges[tot].flow=0;edges[tot].cap=cap;edges[tot].cost=cost;
edges[tot].next=head[from];head[from]=tot;
tot++;
edges[tot].from=to;edges[tot].to=from;edges[tot].flow=0;edges[tot].cap=cap;edges[tot].cost=cost;
edges[tot].next=head[to];head[to]=tot;
tot++;
}
int mfmc()
{
int cost=0,flow=0,i;
int p[maxn];
queue<int> q;
for(;;)
{
for(i=1;i<=n;i++)
{
vis[i]=0;
d[i]=inf;
}
vis[1]=1;d[1]=0;a[1]=inf;
q.push(1);
while(!q.empty())
{
int u=q.front();q.pop();
vis[u]=0;
for(int i=head[u];i!=-1;i=edges[i].next)
{
Edge& e=edges[i];
if(e.cap>e.flow&&d[e.to]>(d[u]+e.cost))
{
d[e.to]=d[u]+e.cost;
p[e.to]=i;
a[e.to]=min(a[u],e.cap-e.flow);
if(!vis[e.to])
{
vis[e.to]=1;
q.push(e.to);
}
}
}
}
if(d[n]==inf) break;
flow+=a[n];
cost+=a[n]*d[n];
if(flow==2) return cost;
for(int x=n;x!=1;)
{
edges[p[x]].flow+=a[n];
edges[p[x]^1].flow-=a[n];
edges[p[x]^1].cost=-edges[p[x]^1].cost;
x=edges[p[x]].from;
}
}
return -1;
}
int main()
{
while(cin>>n>>m)
{
memset(head,-1,sizeof(head));
tot=0;
int i,j,u,v,c;
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&c);
addedge(u,v,1,c);
}
cout<<mfmc()<<endl;
}
return 0;
}

浙公网安备 33010602011771号