hdu 1853 Cyclic Tour(最小费用最大流)

来源:互联网 发布:局域网添加网络打印机 编辑:程序博客网 时间:2024/05/16 01:39
//hdu 1853 Cyclic Tour(最小费用最大流)#include<iostream>#include<cstdio>#include<string.h>#include<queue>using namespace std;const int N=100000;const int Nn=300;const int Inf=99999999;struct node{    int from,to,cap,cost,next;}edge[N];int head[N];int headn;int m;void addedge(int from,int to,int cap,int cost){    edge[headn].from=from;edge[headn].to=to;    edge[headn].cap=cap;edge[headn].cost=cost;    edge[headn].next=head[from];head[from]=headn++;    edge[headn].from=to;edge[headn].to=from;    edge[headn].cap=0;edge[headn].cost=-cost;    edge[headn].next=head[to];head[to]=headn++;}void init(int n){    memset(head,-1,sizeof(head));    headn=0;    int s=0;    int t=n+n+1;    for(int i=1;i<=n;i++)    {        addedge(s,i,1,0);        addedge(n+i,t,1,0);    }}int vis[Nn],father[Nn],dis[Nn];bool SPAH(int s,int t,int n){    queue<int > q;    for(int i=0;i<=n;i++) dis[i]=Inf;    memset(vis,0,sizeof(vis));    memset(father,-1,sizeof(father));    father[s]=-1;    q.push(s);    vis[s]=1;    dis[s]=0;    while(!q.empty())    {        int from=q.front();q.pop();        vis[from]=0;        for(int i=head[from];i!=-1;i=edge[i].next)        {            int to=edge[i].to;            if(edge[i].cap==1&&dis[to]>dis[from]+edge[i].cost)            {                dis[to]=dis[from]+edge[i].cost;                father[to]=i;                if(!vis[to])                {                    q.push(to);                    vis[to]=1;                }            }        }    }    if(dis[t]==Inf) return false;    return true;}int sflow;int mincostmaxflow(int s,int t,int n){    int flow=0;    int minflow=0,mincost=0;    while(SPAH(s,t,n))    {        minflow=Inf+1;        for(int i = father[t]; i != -1; i = father[edge[i].from])            if(edge[i].cap < minflow)                minflow = edge[i].cap;        flow += minflow;        for(int i = father[t]; i != -1; i = father[edge[i].from])        {            edge[i].cap -= minflow;            edge[i^1].cap += minflow;        }        mincost += dis[t] * minflow;    }    sflow = flow;    return mincost;}int main(){    int f,t,c,n;    while(scanf("%d%d",&n,&m)!=EOF)    {        init(n);        for(int i=0;i<m;i++)        {            scanf("%d%d%d",&f,&t,&c);            addedge(f,t+n,1,c);        }        int ans=mincostmaxflow(0,n+n+1,n+n+1);        if(sflow!=n) printf("-1\n");        else printf("%d\n",ans);    }    return 0;}





0 0
原创粉丝点击