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>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, int> PIL;
const int N = 100010;
int n, m, P, Q;
int p[N];
LL sum[N]; // sum[i]表示集合i(i=root)的边权之和
PII temp; // 存任意一条边
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
cin >> n >> m >> P >> Q;
for (int i = 1; i <= n; i++) p[i] = i, sum[i] = 0;
for (int i = 0; i < m; i++) {
int a, b, s;
scanf("%d%d%d", &a, &b, &s);
temp = {a, b};
int pa = find(a), pb = find(b);
if (pa != pb) {
p[pa] = pb;
sum[pb] += sum[pa];
}
sum[pb] += s;
}
priority_queue<PIL, vector<PIL>, greater<PIL>> heap;
int cnt = 0; // 初始时连通分量的个数
for (int i = 1; i <= n; i++) {
if (i == find(i)) {
cnt++;
heap.push({sum[i], i});
}
}
// 判定无解
if (cnt < Q) return 0 * puts("NO");
if (cnt == Q && P > 0 && cnt == n) return 0 * puts("NO");
if (cnt - P > Q) return 0 * puts("NO");
// 一定有解
puts("YES");
while (heap.size() > Q) {
P--;
auto x = heap.top(); heap.pop();
auto y = heap.top(); heap.pop();
int a = x.second, b = y.second;
int pa = find(a), pb = find(b);
cout << pa << " " << pb << endl;
temp = {pa, pb};
p[pa] = pb;
sum[pb] = sum[pb] * 2 + sum[pa] * 2 + 1;
heap.push({sum[pb], pb});
}
// 剩下要连的边在连通块内部连边
while (P--) printf("%d %d\n", temp.first, temp.second);
return 0;
}
|