題目:
Description
Since cables of different types are available and shorter ones are cheaper, it is necessary to make such a plan of hub connection, that the maximum length of a single cable is minimal. There is another problem — not each hub can be connected to any other one because of compatibility problems and building geometry limitations. Of course, Andrew will provide you all necessary information about possible hub connections.
You are to help Andrew to find the way to connect hubs so that all above conditions are satisfied.
Input
Output
Sample Input
4 6 1 2 1 1 3 1 1 4 2 2 3 1 3 4 1 2 4 1
Sample Output
1 4 1 2 1 3 2 3 3 4
題意:求最小生成樹中的最大邊,並且列出用了哪些邊。這道題就是不要被樣例坑到,樣例只是其中一種解釋,因爲樣例也滿足題目要求,並不完全要用成爲一個最小生成樹。
實現:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <queue>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAX = 1005;
int n, m;
struct node {
int u, v, e;
bool friend operator < (node n1, node n2) {
return n1.e > n2.e;
}
}ans[MAX];
int p[MAX];
int _find(int x) {
return p[x] = (p[x] == x ? x : _find(p[x]));
}
int main() {
while(scanf("%d%d", &n, &m) != EOF) {
priority_queue <node> q;
for (int i = 1; i <= n; i++)
p[i] = i;
int v1, v2, value;
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &v1, &v2, &value);
node head;
head.u = v1;
head.v = v2;
head.e = value;
q.push(head);
}
int k = 0;
int maxn = -1;
while (!q.empty()) {
node tt;
tt = q.top();
q.pop();
int x, y;
x = _find(tt.u);
y = _find(tt.v);
if (x != y) {
p[x] = y;
ans[k].u = tt.u;
ans[k].v = tt.v;//記錄邊
k++;
maxn = max(maxn, tt.e);//記錄最大值
}
}
printf("%d\n", maxn);
printf("%d\n", k);
for (int i = 0; i < k; i++) {
printf("%d %d\n", ans[i].u, ans[i].v);
}
}
}