码迷,mamicode.com
首页 > 其他好文 > 详细

HDU3488Tour(KM最小费用圈覆盖)

时间:2015-08-31 19:39:30      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:hdu3488

题意:与HDU1853一样的题目


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<cstdlib>
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define cl(a,b) memset(a,b,sizeof(a));
#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
#define fread(zcc)  freopen(zcc,"r",stdin)
#define fwrite(zcc) freopen(zcc,"w",stdout)
using namespace std;
const int maxn=205;
const int inf=9999999;

int w[maxn][maxn];
int linker[maxn],lx[maxn],ly[maxn],slack[maxn];
bool visx[maxn],visy[maxn];
int nx,ny;

bool dfs(int x){
    visx[x]=true;
    for(int i=0;i<ny;i++){
        if(visy[i])continue;
        int tmp=lx[x]+ly[i]-w[x][i];
        if(tmp==0){
            visy[i]=true;
            if(linker[i]==-1||dfs(linker[i])){
                linker[i]=x;
                return true;
            }
        }else if(slack[i]>tmp){
            slack[i]=tmp;
        }
    }
    return false;
}
int km(){
    cl(linker,-1);
    cl(ly,0);
    for(int i=0;i<nx;i++){
        lx[i]=-inf;
        for(int j=0;j<ny;j++)if(w[i][j]>lx[i]){lx[i]=w[i][j];}
    }
    for(int x=0;x<nx;x++){
        fill(slack,slack+ny+1,inf);
        while(true){
            cl(visx,false);
            cl(visy,false);
            if(dfs(x))break;

            int d=inf;
            for(int i=0;i<ny;i++)if(!visy[i]&&slack[i]<d){
                d=slack[i];
            }
            for(int i=0;i<nx;i++)if(visx[i])lx[i]-=d;
            for(int i=0;i<ny;i++)if(visy[i])ly[i]+=d;
            else slack[i]-=d;
        }
    }
    int ans=0;
    cl(visx,false);
    for(int i=0;i<ny;i++)if(linker[i]!=-1){
        ans+=w[linker[i]][i];
        visx[linker[i]]=true;
        //printf("==%d\n",linker[i]);
    }
    for(int i=0;i<nx;i++)if(!visx[i])return 1;
    if(-ans>inf)return 1;
    return ans;
}

int main(){
    int n,m;
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&n,&m);
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                w[i][j]=-inf;
            }
        }
        for(int i=0;i<m;i++){
            int x,y,v;
            scanf("%d%d%d",&x,&y,&v);
            x--;y--;
            if(-v>w[x][y])w[x][y]=-v;
        }
        nx=ny=n;
        printf("%d\n",-km());
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU3488Tour(KM最小费用圈覆盖)

标签:hdu3488

原文地址:http://blog.csdn.net/u013167299/article/details/48138215

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!