题目大意:
给定各村间的距离,用最少话费修建通路联通所有村,并得到修建路中最长的那一段。

 

这一题和之前HDU 1102题极其相似,可我在这用了同样的Kruscal算法却达到了800+ms的时间

我的代码:

 1 #include <iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 
 7 #define N 505
 8 
 9 int fa[N];
10 int map[N][N];
11 
12 struct Path{
13     int x,y,d;
14     bool operator<(const Path &m)const{
15         return d<m.d;
16     }
17 }path[250000];
18 
19 int getHead(int x)
20 {
21     int a=x;
22     while(x!=fa[x]) x=fa[x];
23     fa[a]=x;
24     return x;
25 }
26 
27 bool Union(int x,int y)
28 {
29     int fa_x=getHead(x);
30     int fa_y=getHead(y);
31     if(fa_x==fa_y) return false;
32     fa[fa_x]=fa_y;
33     return true;
34 }
35 
36 int main()
37 {
38     int T,n,k,ans;
39     cin>>T;
40     while(T--){
41         scanf("%d",&n);
42         for(int i=1;i<=n;i++) fa[i]=i;//初始化父节点
43         for(int i=1;i<=n;i++){
44             for(int j=1;j<=n;j++)
45                 cin>>map[i][j];
46         }
47 
48         k=1;
49         for(int i=1;i<=n;i++){
50             for(int j=1;j<i;j++){
51                 path[k].x=i,path[k].y=j;
52                 path[k++].d=map[i][j];
53             }
54         }
55 
56         sort(path+1,path+k);
57 
58         for(int i=1;i<k;i++)
59             if(Union(path[i].x,path[i].y)) ans=path[i].d;
60 
61         cout<<ans<<endl;
62     }
63     return 0;
64 }
View Code

相关文章: