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

//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
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

u014068781

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值