0%

HDU - 1233-还是畅通工程 

思路讲解

无向图判环模版题

无向图判环+贪心选择短边,这就是kruskal算法

AC代码

https://vjudge.net/solution/57384651

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <cstring>
#include <algorithm>
#include <deque>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <cmath>
#include <bitset>
#include <iterator>
#include <random>
#include <iomanip>
#include <cctype>
#include <array>

typedef long long ll;
typedef std::pair<ll,ll> pll;
typedef std::array<ll,3> arr;
const ll MAXN=110;
ll fa[110];

ll N;
struct cmp{
bool operator()(arr a,arr b){
if(a[2]!=b[2])
return a[2]>b[2];
return false;
}
};

inline void init(){
for(int i=0;i<N+7;++i)
fa[i]=i;
}

inline ll find(ll x){
if(fa[x]==x)
return x;
fa[x]=find(fa[x]);
return fa[x];
}

void solve(){
init();
std::priority_queue<arr,std::vector<arr>,cmp> pq;
for(int i=1;i<=N*(N-1)/2;++i){
ll a,b,c;
std::cin>>a>>b>>c;
pq.push({a,b,c});
}
ll ans=0;
while (!pq.empty()) {
ll a=pq.top()[0],b=pq.top()[1],c=pq.top()[2];
pq.pop();
if(find(a)!=find(b)){
fa[find(a)]=find(b);
ans+=c;
}
}
std::cout<<ans<<"\n";
return;
}

int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);std::cout.tie(0);
while (std::cin>>N) {
if(N==0){
break;
}
solve();
}
return 0;
}
/*
AC https://vjudge.net/solution/57384651
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0

*/

心路历程(WA,TLE,MLE……)