标签:
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5359 Accepted Submission(s): 2327
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 #include<cmath> 6 using namespace std; 7 const int INF=0x7f7f7f7f; 8 const int MAXN=210; 9 const int MAXM=1010; 10 int pre[MAXN]; 11 struct Node{ 12 int u,v,d; 13 }; 14 Node dt[MAXM]; 15 int cmp(Node a,Node b){ 16 return a.d<b.d; 17 } 18 int find(int x){ 19 int r=x; 20 while(r!=pre[r])r=pre[r]; 21 // pre[x]=r; 22 return r; 23 } 24 int main(){ 25 int n,m; 26 while(~scanf("%d%d",&n,&m)){ 27 for(int i=0;i<m;i++){ 28 scanf("%d%d%d",&dt[i].u,&dt[i].v,&dt[i].d); 29 } 30 sort(dt,dt+m,cmp); 31 int Q,s,e,f1,f2; 32 scanf("%d",&Q); 33 while(Q--){ 34 int ans=INF;//这个竟然被我写到外边 35 scanf("%d%d",&s,&e); 36 for(int j=0;j<m;j++){ 37 for(int i=1;i<=n;i++)pre[i]=i; 38 for(int i=j;i<m;i++){ 39 int u=dt[i].u,v=dt[i].v,d=dt[i].d; 40 f1=find(u);f2=find(v); 41 if(f1!=f2)pre[f2]=f1; 42 if(find(s)==find(e)){ 43 ans=min(ans,d-dt[j].d); 44 break; 45 } 46 } 47 } 48 if(ans==INF)puts("-1"); 49 else printf("%d\n",ans); 50 } 51 } 52 return 0; 53 }
find the most comfortable road(并差集,找差值最小的权值)
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/4905686.html