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

题目链接:

点击打开链接

题目链接:

给出一张图,许多有向边,将图分成几个环路进行周游,问最小花费是多少

题目分析:

因为环的性质导致图中的每个点的度数均为1,所以只需要为每个点选择一条花费最小的入边即可,切不能重复使用一条边,直接将每座城市拆点,然后源点连向每座城市的第一个点,容量为1,每个城市的第二个点连向汇点,容量为1,花费为0,然后每条边就是对应起点拆完的第一个点连向终点拆完的第二个点连接,容量为1,花费为路径长度,但是注意的是,这道题中会出现重边,所以如果采用邻接矩阵的话,要保留最小的边

代码如下:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
#define MAX 207
#define INF 0x7fffffff

using namespace std;

int flow[MAX][MAX];
int cost[MAX][MAX];
int pre[MAX],dis[MAX];
int minflow[MAX],mark[MAX];

int spfa ( int start , int end )
{
    queue<int> q;
    memset ( mark , 0 , sizeof ( mark ));
    memset ( pre , -1 , sizeof ( pre ));
    for ( int i = 0 ; i < MAX ; i++ )
        dis[i] = minflow[i] = INF;
    q.push ( start );
    dis[start] = 0;
    mark[start] = 1;
    while ( !q.empty())
    {
        int u = q.front();
        q.pop();
        mark[u] = 0;
        for ( int i = 0 ; i <= end ; i++ )
            if ( flow[u][i]&&dis[i] > dis[u] + cost[u][i] )
        {
            dis[i] = dis[u] + cost[u][i];
            pre[i] = u;
            minflow[i] = min ( minflow[u] , flow[u][i]);
            if ( !mark[i] )
            {
                mark[i] = 1;
                q.push ( i );
            }
        }
    }
    return dis[end] != INF;
}

int maxflow_mincost ( int start , int end )
{
    int i,x,ans = 0;
    int temp = 0;
    while ( spfa ( start , end ) )
    {
        x = end;
        while ( pre[x] != -1 )
        {
            flow[pre[x]][x] -= minflow[end];
            flow[x][pre[x]] += minflow[end];
            x = pre[x];
        }
        ans += dis[end];
        temp++;
    }
    if ( temp == (end-1)/2 ) return ans;
    else return -1;
}

int main ( )
{
    int a,b,c,n,m;
    while (~scanf ( "%d%d" , &n , &m ))
    {
        int s = 0 , e = 2*n+1;
        memset ( flow , 0 , sizeof ( flow ));
        memset ( cost , 0 , sizeof ( cost ));
        for ( int i = 1 ; i <= n ; i++ )
        {
            flow[s][i] = 1;
            flow[i+n][e] = 1;
        }
        while ( m-- )
        {
            scanf ( "%d%d%d" , &a , &b , &c );
            flow[a][b+n] = 1;
            if ( !cost[a][b+n ] )
                cost[a][b+n] = c;
            else cost[a][b+n] = min ( c , cost[a][b+n]);
            cost[b+n][a] = -cost[a][b+n];
        }
        printf ( "%d\n" , maxflow_mincost ( s , e ));
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值