hdu3488 Tour 拆点+二分图最佳匹配

In the kingdom of Henryy, there are N (2 <= N <= 200) cities, with M (M <= 30000) one-way roads connecting them. You are lucky enough to have a chance to have a tour in the kingdom. The route should be designed as: The route should contain one or more loops. (A loop is a route like: A->B->……->P->A.)
Every city should be just in one route.
A loop should have at least two cities. In one route, each city should be visited just once. (The only exception is that the first and the last city should be the same and this city is visited twice.)
The total distance the N roads you have chosen should be minimized.

题意:循环访问一个国家的所有城市,城市之间有边,求最小的花费

把所有城市拆成入点和出点,然后进行二分图最佳匹配即可。

 #include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=;
int g[maxn][maxn],match[maxn],lx[maxn],ly[maxn],visx[maxn],visy[maxn],s[maxn],n,m;
bool hungary(int u){
visx[u]=;
for(int i=;i<=n;++i){
if(!visy[i]&&lx[u]+ly[i]==g[u][i]){
visy[i]=;
if(!match[i]||hungary(match[i])){
match[i]=u;
return ;
}
}
else if(!visy[i])s[i]=min(s[i],lx[u]+ly[i]-g[u][i]);
}
return ;
}
int KM(){
for(int i=;i<=n;++i){
for(int j=;j<=n;++j)s[j]=INF;
while(){
memset(visx,,sizeof(visx));
memset(visy,,sizeof(visy));
if(hungary(i))break;
int d=INF;
for(int j=;j<=n;++j)
if(!visy[j])d=min(d,s[j]);
for(int j=;j<=n;++j){
if(visx[j])lx[j]-=d;
if(visy[j])ly[j]+=d;
else s[j]-=d;
}
}
}
int ans=;
for(int i=;i<=n;++i)ans+=g[match[i]][i];
return ans;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
memset(lx,,sizeof(lx));
memset(ly,,sizeof(ly));
memset(match,,sizeof(match));
memset(g,0xc0,sizeof(g));
for(int i=;i<=m;++i){
int a,b,v;
scanf("%d%d%d",&a,&b,&v);
if(-v>g[a][b])g[a][b]=-v;
}
for(int i=;i<=n;++i){
for(int j=;j<=n;++j){
lx[i]=max(lx[i],g[i][j]);
}
}
printf("%d\n",-KM());
}
return ;
}
上一篇:使用awstats统计分析tengine日志访问量及各种http网站数据


下一篇:Java中的锁[原理、锁优化、CAS、AQS]