DU-1598-find the most comfortable road(
阿新 • • 發佈:2018-11-01
思路:把邊排序,列舉起點,並查集判斷 是否U,V連上(判斷終點),終點-起點就是答案。
#include<bits/stdc++.h> using namespace std; struct Edg { int u, v, w; bool operator < (const Edg &p) const { return w < p.w; } }edg[2000]; int Father[2000]; int FindFather(int x) { return Father[x] <0? x: FindFather(Father[x]); } void Umerge(int x,int y) { int Fx = FindFather(x), Fy = FindFather(y); if (Fx != Fy)Father[Fx] = Fy; } int main() { ios_base::sync_with_stdio(0); int n, m; while (cin>>n&&n) { cin >> m; for (int i = 0; i<m; i++) cin>>edg[i].u>>edg[i].v>>edg[i].w; sort(edg, edg + m); int u, v, Q; cin >> Q; while (Q--) { cin >> u >> v; int ans = INT_MAX; for (int i = 0; i<m; i++) { memset(Father, -1, sizeof(Father)); for (int j = i; j<m; j++) { Umerge(edg[j].u,edg[j].v); if (FindFather(u) == FindFather(v)) { ans = min(ans, edg[j].w - edg[i].w); break; } } } ans == INT_MAX ?printf("-1\n"):printf("%d\n", ans); } } return 0; }