并查集 + 贪心 + 快速排序 求最小生成树 #include <iostream> #include <memory> #define MAX_HUB_NUM 1005 #define MAX_EDGE_NUM 15005 using namespace std; int edge[3][MAX_EDGE_NUM + 1]; int head[MAX_HUB_NUM + 1]; int resEdge[MAX_EDGE_NUM + 1]; int hub_num; int edge_num; void swap1(int pos1, int pos2) { int temp0 = edge[0][pos2]; int temp1 = edge[1][pos2]; int temp2 = edge[2][pos2]; edge[0][pos2] = edge[0][pos1]; edge[1][pos2] = edge[1][pos1]; edge[2][pos2] = edge[2][pos1]; edge[0][pos1] = temp0; edge[1][pos1] = temp1; edge[2][pos1] = temp2; } void swap2(int pos1, int pos2) { int temp = resEdge[pos2]; resEdge[pos2] = resEdge[pos1]; resEdge[pos1] = temp; } int comp1(int pos1, int pos2) { if(edge[0][pos1] < edge[0][pos2]) return -1; else if(edge[0][pos1] == edge[0][pos2]) return 0; else return 1; } int comp2(int p1, int p2) { int pos1 = resEdge[p1]; int pos2 = resEdge[p2]; if(edge[1][pos1] < edge[1][pos2]) return -1; else if(edge[1][pos1] == edge[1][pos2]) { if(edge[2][pos1] < edge[2][pos2]) return -1; else if(edge[2][pos1] == edge[2][pos2]) return 0; else return 1; } else return 1; } void fast_sort(int start, int end, int (*comp)(int pos1, int pos2), void (*swap)(int pos1, int pos2)) { if(start < end) { int pos_s = start; int pos_e = end + 1; while(true) { while(++pos_s < end && comp(start, pos_s) == 1); while(--pos_e > start && comp(start, pos_e) == -1); if(pos_s < pos_e) swap(pos_s, pos_e); else break; } swap(start, pos_e); fast_sort(start, pos_e - 1, comp, swap); fast_sort(pos_e + 1, end, comp, swap); } } void init_input() { memset(edge, 0, sizeof(edge)); memset(head, 0, sizeof(head)); memset(resEdge, 0, sizeof(resEdge)); cin>>hub_num>>edge_num; for(int i = 1; i <= edge_num; i++) { cin>>edge[1][i]>>edge[2][i]>>edge[0][i]; if(i <= hub_num) head[i] = i; } fast_sort(1, edge_num, &comp1, &swap1); } int find(int x) { if(head[x] == x) return x; else return find(head[x]); } void join(int x, int y) { int head1 = find(x); int head2 = find(y); head[head1] = head2; } int main() { int i = 1; int total = 0; int maxv = 0; int pos1, pos2, curVal; init_input(); while(i <= edge_num && total < (hub_num - 1)) { curVal = edge[0][i]; pos1 = find(edge[1][i]); pos2 = find(edge[2][i]); if(pos1 != pos2) { if(curVal > maxv) maxv = curVal; join(pos1, pos2); total ++; resEdge[total] = i; } i++; } cout<<maxv<<endl; cout<<total<<endl; fast_sort(1, total, &comp2, &swap2); for(i = 1; i <= total; i++) { cout<<edge[1][resEdge[i]]<<" "<<edge[2][resEdge[i]]<<endl; } return 0; }