标签:des style blog http color java os io
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3720 Accepted Submission(s): 1583
并查集的做法
将每一条边按照speed升序排序,然后从小到大枚举每一条边直到起点和终点在同一个集合,再更新 speed最大值-最小值 即可
1 #include<cstdio> 2 #include<cstring> 3 #include<stdlib.h> 4 #include<algorithm> 5 using namespace std; 6 const int MAXN=1000+10; 7 const int INF=0x3f3f3f3f; 8 9 struct node 10 { 11 int x,y; 12 int val; 13 bool operator <(const node&B)const 14 { 15 return val<B.val; 16 } 17 }a[MAXN]; 18 int p[MAXN]; 19 20 int Find(int x) 21 { 22 return p[x]==x?x:p[x]=Find(p[x]); 23 } 24 25 int main() 26 { 27 //freopen("in.txt","r",stdin); 28 int n,m; 29 while(scanf("%d %d",&n,&m)!=EOF) 30 { 31 for(int i=1;i<=m;i++) 32 scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].val); 33 sort(a+1,a+m+1);//按照speed升序排序 34 int kase,star,en,minn; 35 scanf("%d",&kase); 36 while(kase--) 37 { 38 scanf("%d %d",&star,&en); 39 minn=INF;//minn的初始化要放外面,一开始放里面wa了一次,因为如果放里面的话minn就得不到更新 40 for(int i=1;i<=m;i++)//更新最小值 41 { 42 for(int k=1;k<=m;k++) 43 p[k]=k; 44 for(int j=i;j<=m;j++)//寻找能使起点终点连通的最大值 45 { 46 int x=Find(a[j].x); 47 int y=Find(a[j].y); 48 if(x!=y) 49 p[x]=y; 50 if(Find(star)==Find(en)) 51 { 52 minn=min(minn,a[j].val-a[i].val);//因为排了序,所以必定a[i].val>=a[i].val 53 break; 54 } 55 } 56 if(minn==INF)//如果第一次不能更新minn说明起点和终点不能连通 57 break; 58 } 59 if(minn==INF) 60 printf("-1\n"); 61 else 62 printf("%d\n",minn); 63 } 64 } 65 return 0; 66 }
最短路的做法
HDU 1598 find the most comfortable road (并查集||最短路),布布扣,bubuko.com
HDU 1598 find the most comfortable road (并查集||最短路)
标签:des style blog http color java os io
原文地址:http://www.cnblogs.com/clliff/p/3906628.html