标签:
解题思路:典型的Kruskal,不能用floyed(会超时),上代码:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 #define inf 0x3f3f3f3f 6 const int maxn = 1005; 7 int father[maxn]; 8 9 struct node{ 10 int x, y, w; 11 }p[maxn*maxn]; //第一次开maxn,RE了一次 12 13 int cmp(node A, node B) 14 { 15 return A.w > B.w; //权值从大到小排序 16 } 17 18 int Find(int x) 19 { 20 return father[x] == x ? x : father[x] = Find(father[x]); 21 } 22 23 void Union(int x, int y) 24 { 25 int rootx = Find(x); 26 int rooty = Find(y); 27 if(rootx != rooty) father[rootx] = rooty; 28 return ; 29 } 30 31 int main() 32 { 33 int t, n, m, kase = 1; 34 scanf("%d", &t); 35 while(t--) 36 { 37 scanf("%d %d", &n, &m); 38 for(int i = 1; i <= n; i++) father[i] = i; 39 for(int i = 1; i <= m; i++) 40 scanf("%d %d %d", &p[i].x, &p[i].y, &p[i].w); 41 sort(p+1, p+1+m, cmp); //注意这里是p+1开始 42 43 int ans = inf; //初始化ans为最大值 44 for(int i = 1; i <= m; i++) 45 { 46 int rootx = Find(p[i].x); 47 int rooty = Find(p[i].y); 48 if(rootx != rooty) 49 { 50 Union(rootx, rooty); 51 //ans保存路径中最小的权值 52 if(p[i].w < ans) ans = p[i].w; 53 //如果1和n已经连接,则直接跳出 54 if(Find(1) == Find(n)) break; 55 } 56 } 57 //注意输出格式 58 printf("Scenario #%d:\n%d\n\n", kase++, ans); 59 } 60 return 0; 61 }
标签:
原文地址:http://www.cnblogs.com/loveprincess/p/4904985.html