题意:每两个点之间都有一个速度,求a点到b点速度之差最小是多少,如果到达不了输出-1;
思路:先按照速度排序,并查集(最小生成树思路)一直到a,b联通,然后求最大速度和最小速度的差,这个要暴力,每条边都建立最小生成树,最后找到一个最小的速度差
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int father[220]; int rank[220]; struct bian { int start; int end; int w; }B[1002]; void Make_set(int n) { int i; for(i = 1; i <= n; i++) { rank[i] = 0; father[i] = i; } } int Find_set(int x) { if(x != father[x]) { father[x] = Find_set(father[x]); } return father[x]; } void Union(int x,int y) { int xx = Find_set(x); int yy = Find_set(y); if(xx == yy) return ; else { if(rank[xx] > rank[yy]) { father[yy] = xx;rank[xx] += rank[yy]; } else if(rank[yy] > rank[xx]) { father[xx] = yy,rank[yy] += rank[xx]; } else { father[yy] = xx ,rank[xx]++; } } } bool cmp(bian a,bian b) { if(a.w < b.w) return true; else return false; } int main() { int n,m; while(scanf("%d%d",&n,&m) != EOF) { int i; for(i = 1; i <= m; i++) { scanf("%d%d%d",&B[i].start,&B[i].end,&B[i].w); } sort(B+1,B+m+1,cmp); int count; scanf("%d",&count); while(count--) { int start,end; scanf("%d%d",&start,&end); int i,j,ans=9999999; for(i = 1; i <= m; i++) { Make_set(n); for(j = i; j <= m; j++) { Union(B[j].start,B[j].end); if(Find_set(start) == Find_set(end)) { break; } } if(j > m) break; if(ans > B[j].w - B[i].w) ans = B[j].w - B[i].w; } if(ans != 9999999) printf("%d\n",ans); else printf("-1\n"); } } return 0; }