-
Notifications
You must be signed in to change notification settings - Fork 0
/
L06-4.cpp
129 lines (105 loc) · 2.13 KB
/
L06-4.cpp
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define PUB push_back
#define fi first
#define se second
struct apa{
int u, v, tipe;
};
int N, M, K, bthBatu, bthBeton;
int bykBatu = 0, bykBeton = 0;
int hbgBatu[20005], hbgBeton[20005];
bool isUrgent[100005];
bool isAmbil[100005];
vector<apa>jalan;
int prn[20005];
int find_prn(int a){
if(prn[a] == a) return a;
else return prn[a] = find_prn(prn[a]);
}
bool isSame(int a, int b){
return (find_prn(a) == find_prn(b));
}
void joinSet(int a, int b){
int prnA = find_prn(a),
prnB = find_prn(b);
if(prnA == prnB) return;
prn[prnA] = prnB;
}
bool cmp(apa a, apa b){
return a.tipe < b.tipe;
}
void find_urgent(){
for(int i=0;i<M;i++){
if(jalan[i].tipe == 1){
if(!isSame(jalan[i].u, jalan[i].v)){
joinSet(jalan[i].u, jalan[i].v);
}
}
}
for(int i=0;i<M;i++){
if(jalan[i].tipe == 0){
if(!isSame(jalan[i].u, jalan[i].v)){
isUrgent[i] = 1;
joinSet(jalan[i].u, jalan[i].v);
}
}
}
}
int main(){
for(int i=0;i<20005;i++) prn[i] = i;
cin >> N >> M >> K;
bthBatu = K;
bthBeton = N-K-1;
for(int i=0;i<M;i++){
int x, y, z;
cin >> x >> y >> z;
jalan.PUB({x, y, z});
if(z == 0){
hbgBatu[x]++;
hbgBatu[y]++;
bykBatu++;
}else{
hbgBeton[x]++;
hbgBeton[y]++;
bykBeton++;
}
}
sort(jalan.begin(), jalan.end(), cmp);
find_urgent();
for(int i=1;i<=N;i++) prn[i] = i;
// Ambil yang urgent
for(int i=0;i<M;i++){
if(bthBatu > 0 && isUrgent[i]){
joinSet(jalan[i].u, jalan[i].v);
isAmbil[i] = 1;
bthBatu--;
}
}
// MST biasa
for(int i=0;i<M;i++){
if(!isAmbil[i]){
if(jalan[i].tipe == 0 && bthBatu > 0){
if(!isSame(jalan[i].u, jalan[i].v)){
isAmbil[i] = 1;
bthBatu--;
joinSet(jalan[i].u, jalan[i].v);
}
}else if(jalan[i].tipe == 1 && bthBeton > 0){
if(!isSame(jalan[i].u, jalan[i].v)){
isAmbil[i] = 1;
bthBeton--;
joinSet(jalan[i].u, jalan[i].v);
}
}
}
}
for(int i=1;i<=N;i++) if(!isSame(1, i)){
cout << "no solution" << endl;
return 0;
}
for(int i=0;i<M;i++)
if(isAmbil[i])
cout << jalan[i].u << " " << jalan[i].v << " " << jalan[i].tipe << endl;
}