题目链接 http://vjudge.net/problem/POJ-1861
解题思路
用Kruskal算法可以比较轻松地得到每次连接的边
但是我用了1000ms过的。。。(时限1000ms(⊙﹏⊙)b)可能是我写挫了吧
代码
#include<iostream> #include<algorithm> using namespace std; const int MAX_SIZE = 1010; const int INF = 1e9 + 7; struct node { int x, y; int value; }p[15010], edge[15010]; int father[MAX_SIZE]; int n, m; int maxEdge; void read() { for(int i=0; i<m; i++) { cin >> p[i].x >> p[i].y >> p[i].value; } } void make() { for(int i=1; i<=n; i++) father[i] = i; } int find(int x) { if(x != father[x]) father[x] = find(father[x]); return father[x]; } bool cmp(node a, node b) { if(a.x != b.x) return a.x < b.x; else if(a.y != b.y) return a.y < b.y; } bool cmp1(node a, node b) { return a.value < b.value; } int kru() { int cnt = 0; make(); for(int i=0; i<m; i++) { int xf = find(p[i].x); int yf = find(p[i].y); if(xf == yf) continue; father[xf] = yf; if(p[i].value > maxEdge) maxEdge = p[i].value; edge[cnt].x = p[i].x; edge[cnt].y = p[i].y; cnt++; } return cnt; } int main() { cin >> n >> m; read(); sort(p, p+m, cmp1); int cnt = kru(); //sort(edge, edge+cnt, cmp); cout << maxEdge << endl; cout << cnt << endl; for(int i=0; i<cnt; i++) cout << edge[i].x << " " << edge[i].y << endl; return 0; }
时间: 2024-10-11 16:19:33