sicily 1090

最小生成树

 

#include <iostream> #include <cstring> using namespace std; #define MAX 65537 int adj[500][500]; bool isVis[500]; int lowcost[500]; int main() { int cases, n; cin >> cases; while(cases--) { cin >> n; int max = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cin >> adj[i][j]; } } memset(isVis, false, sizeof(isVis)); isVis[0] = true; for(int i = 0; i < n; i++) { lowcost[i] = adj[0][i]; } for(int i = 1; i < n; i++) { int min = MAX; int minIndex = 0; for(int j = 0; j < n; j++) { if(!isVis[j] && lowcost[j] < min) { min = lowcost[j]; minIndex = j; } } isVis[minIndex] = true; if(min > max) max = min; for(int j = 0; j < n; j++) { if(!isVis[j] && adj[minIndex][j] < lowcost[j]) lowcost[j] = adj[minIndex][j]; } } cout << max << endl; if(cases != 0) cout << endl; } return 0; } 

找父节点是翻版陈泽裕的

#include <iostream> #include <cstring> #include <algorithm> using namespace std; #define MAX 65537 struct node { int x; int y; int weight; }edge[125000]; bool isVis[500]; int fa[500]; bool cmp(node a, node b) { return a.weight < b.weight; } int getfather(int x) { return fa[x] == x ? x : fa[x] = getfather(fa[x]); } int main() { int cases, n; cin >> cases; while(cases--) { cin >> n; int weight; int num = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cin >> weight; if(i < j) { edge[num].x = i; edge[num].y = j; edge[num].weight = weight; num++; } } } sort(edge, edge + num, cmp); memset(isVis, false, sizeof(isVis)); int max = 0; int e = 0; for(int i = 0; i < n; i++) fa[i] = i; for(int i = 0; i < num && e < n - 1; i++) { int x = getfather(edge[i].x); int y = getfather(edge[i].y); if(x != y) { e++; if(edge[i].weight > max) max = edge[i].weight; fa[x] = y; } } cout << max << endl; if(cases != 0) cout << endl; } return 0; } 

你可能感兴趣的:(sicily 1090)