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.

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

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

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<math.h>
 5 using namespace std;
 6 const int INF=0x3f3f3f3f;
 7 const int maxn=505;
 8 int g[maxn][maxn],match[maxn],lx[maxn],ly[maxn],visx[maxn],visy[maxn],s[maxn],n,m;
 9 bool hungary(int u){
10     visx[u]=1;
11     for(int i=1;i<=n;++i){
12         if(!visy[i]&&lx[u]+ly[i]==g[u][i]){
13             visy[i]=1;
14             if(!match[i]||hungary(match[i])){
15                 match[i]=u;
16                 return 1;
17             }
18         }
19         else if(!visy[i])s[i]=min(s[i],lx[u]+ly[i]-g[u][i]);
20     }
21     return 0;
22 }
23 int KM(){
24     for(int i=1;i<=n;++i){
25         for(int j=1;j<=n;++j)s[j]=INF;
26         while(1){
27             memset(visx,0,sizeof(visx));
28             memset(visy,0,sizeof(visy));
29             if(hungary(i))break;
30             int d=INF;
31             for(int j=1;j<=n;++j)
32                 if(!visy[j])d=min(d,s[j]);
33             for(int j=1;j<=n;++j){
34                 if(visx[j])lx[j]-=d;
35                 if(visy[j])ly[j]+=d;
36                 else s[j]-=d;
37             }
38         }
39     }
40     int ans=0;
41     for(int i=1;i<=n;++i)ans+=g[match[i]][i];
42     return ans;
43 }
44 int main(){
45     int T;
46     scanf("%d",&T);
47     while(T--){
48         scanf("%d%d",&n,&m);
49         memset(lx,0,sizeof(lx));
50         memset(ly,0,sizeof(ly));
51         memset(match,0,sizeof(match));
52         memset(g,0xc0,sizeof(g));
53         for(int i=1;i<=m;++i){
54             int a,b,v;
55             scanf("%d%d%d",&a,&b,&v);
56             if(-v>g[a][b])g[a][b]=-v;
57         }
58         for(int i=1;i<=n;++i){
59             for(int j=1;j<=n;++j){
60                 lx[i]=max(lx[i],g[i][j]);
61             }
62         }
63         printf("%d
",-KM());
64     }
65     return 0;
66 }
View Code
原文地址:https://www.cnblogs.com/cenariusxz/p/6592554.html