学习了一下最小费用最大流,发现其实就是在原来每条边的定义加上一个单位流量的费用,so寻找增广路时采用贪心的思想,每次找费用和最小的路径即可。
废话少说,上代码:
//POJ2135
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#define maxn 1005
#define maxm 10005
#define INF 0x7ffffff//被fff坑死QAQ~~~
using namespace std;
int flow,u,v,cost,n,m,id[maxn],head[maxn],q,s,t,x,y,num,d[maxn],inq[maxn],a[maxn],pre[maxn];
struct xx{
int v,next,cap,cost;
}b[maxm*4];
void add(int u,int v ,int q,int cost)
{
b[num]=(xx){v,head[u],q,cost};
head[u]=num++;
b[num]=(xx){u,head[v],0,-cost};
head[v]=num++;
}
int Bellford(int s,int t,int& flow,int& cost)
{
//memset(d,INF,sizeof(d));
for (int i=0;i<=t;i++) d[i]=INF;
memset(inq,0,sizeof(inq));
d[s]=0;inq[s]=1;pre[s]=-1;a[s]=INF;id[s]=-1;
queue <int> q;
q.push(s);
while(!q.empty())
{
int u=q.front();q.pop();
inq[u]=0;
for (int i=head[u];i!=-1;i=b[i].next)
{
int v=b[i].v;
if (d[u]+b[i].cost<d[v]&&b[i].cap)
{
d[v]=d[u]+b[i].cost;
pre[v]=u;
id[v]=i;
a[v]=min(a[u],b[i].cap);
if (!inq[v]) inq[v]=1,q.push(v);
}
}
}
if (d[t]==INF) return 0;
flow+=a[t];
cost+=d[t]*a[t];
u=t;
while (u!=s)
{
b[id[u]].cap-=a[t];
b[id[u]^1].cap+=a[t];
u=pre[u];
}
return true;
}
int Mincost()
{
flow=0,cost=0;
while (Bellford(s,t,flow,cost));
return cost;
}
int main()
{
scanf("%d%d",&n,&m);
num=0;s=0;t=n+1;
memset(head,-1,sizeof(head));
for (int i=1;i<=m;i++)
scanf("%d%d%d",&x,&y,&q),add(x,y,1,q),add(y,x,1,q);
add(s,1,2,0);add(n,t,2,0);
printf("%d",Mincost());
return 0;
}