Cyclic Tour(最小权值环)

传送门HDU1853

描述

There are N cities in our country, and M one-way roads connecting them. Now Little Tom wants to make several cyclic tours, which satisfy that, each cycle contain at least two cities, and each city belongs to one cycle exactly. Tom wants the total length of all the tours minimum, but he is too lazy to calculate. Can you help him?

输入

There are several test cases in the input. You should process to the end of file (EOF).
The first line of each test case contains two integers N (N ≤ 100) and M, indicating the number of cities and the number of roads. The M lines followed, each of them contains three numbers A, B, and C, indicating that there is a road from city A to city B, whose length is C. (1 ≤ A,B ≤ N, A ≠ B, 1 ≤ C ≤ 1000).

输出

Output one number for each test case, indicating the minimum length of all the tours. If there are no such tours, output -1.

样例

  • Input
    6 9
    1 2 5
    2 3 5
    3 1 10
    3 4 12
    4 1 8
    4 6 11
    5 4 7
    5 6 9
    6 5 4
    6 5
    1 2 1
    2 3 1
    3 4 1
    4 5 1
    5 6 1
  • Output
    42
    -1

题解

  • 题意:给出n个点,m条边,两个点之间可能会有多条边,在图中找出几个环,每个点仅属于一个环,每个环至少两个点,求划分后这些环的最小权值和,如果有的点无法构成环,则输出-1。
  • 对于一个环,每个点的出度和入度都是1,把每个点的出度和入度分开,构成二分图。如果某几个点构成完美匹配,则这几个点可构成一个环。这样问题就变成了找最小权值和的完美匹配,如果没有完美匹配,则输出-1。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<bits/stdc++.h>
#define INIT(a,b) memset(a,b,sizeof(a))
#define LL long long
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e2+7;
const int mod=1e9+7;
int line[maxn][maxn],wx[maxn],wy[maxn],visx[maxn],visy[maxn],match[maxn];
int n,m,minsub;
int Find(int x){
visx[x]=1;
for(int i=1;i<=n;i++){
if(visy[i])continue;
int t=wx[x]+wy[i]-line[x][i];
if(t==0){
visy[i]=1;
if(!match[i]||Find(match[i])){
match[i]=x;
return true;
}
}
else minsub=min(minsub,t);
}
return false;
}
int Km(){
for(int i=1;i<=n;i++){
while(1){
minsub=inf;
INIT(visx,0);INIT(visy,0);
if(Find(i)) break;
for(int j=1;j<=n;j++){
if(visx[j]) wx[j]-=minsub;
if(visy[j]) wy[j]+=minsub;
}
}
}
int ans=0;
for(int i=1;i<=n;i++){
if(line[match[i]][i]==-inf) return -1; //两点间无边
ans+=line[match[i]][i];
}
return -ans;
}
int main(){
int x,y,w;
while(~scanf("%d%d",&n,&m)){
INIT(match,0);INIT(wy,0);
for(int i=1;i<=n;i++){
wx[i]=-inf;
for(int j=1;j<=n;j++)
line[i][j]=-inf;
}
for(int i=1;i<=m;i++){
scanf("%d%d%d",&x,&y,&w);
line[x][y]=max(line[x][y],-w);
wx[x]=max(wx[x],-w);
}
printf("%d\n",Km());

}

return 0;
}
Donate comment here