3
AC代码如下:
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> using namespace std; #define INF1 1000000000000000001 #define INF2 1000000009 const int maxn = 100010; struct node{ int s,e,w; }map[maxn]; long long d[201][201]; long long fa[maxn]; int n, m; int h[maxn]; void init(int a) { for(int i = 0; i <= a; i++) { fa[i] = i; h[i] = 0; } for(int i = 0; i <= a; i++){ map[i].w = INF2; } } int Find(int x) { if(fa[x] == x) return x; else return fa[x] = Find(fa[x]); } void unite(int x,int y) { x = Find(fa[x]); y = Find(fa[y]); if(x == y) return; else { if(h[x] > h[y]) fa[y] = fa[x]; else { fa[x] = fa[y]; if(h[x] == h[y]) h[y]++; } } } bool M[maxn]; int s[maxn]; int r; void discretize(){ memset(M, false, sizeof(M)); //memset(s, 0, sizeof(s)); int k; for(int i = 1; i <= n; i++){ k = Find(i); if(!M[k]){ s[k] = r++; M[k] = true; } } for(int i = 1; i < r; i++){ for(int j = 1; j < r; j++){ if(i == j) d[i][j] = 0; else d[i][j] = INF1; } } for(int j = 1; j <= m; j++){ if(map[j].w != 0){ int dx = Find(map[j].s); int dy = Find(map[j].e); dx = s[dx]; dy = s[dy]; d[dx][dy] = d[dy][dx] = min(d[dx][dy],(long long)map[j].w); //cout<<"*"<<d[dx][dy]<<"*"<<endl; } } } void floyd(int r){ for(int k = 1; k < r; k++) for(int i = 1; i < r; i++) for(int j = 1; j < r; j++){ if(d[i][k] < INF1 && d[k][j] < INF1) d[i][j] = min(d[i][k] + d[k][j], d[i][j]); } } void input(int m){ for(int i = 1; i <= m; i++){ int a , b; scanf("%d%d",&map[i].s, &map[i].e); scanf("%d",&map[i].w); if(map[i].w == 0) unite(map[i].s, map[i].e); } } int main(){ while(cin>>n>>m&&n){ init(n); input(m); r = 1; discretize(); floyd(r); int q; cin>>q; while(q--){ int a, b; scanf("%d%d",&a, &b); a = Find(a); b = Find(b); a = s[a]; b = s[b]; if(d[a][b] == INF1) printf("-1\n"); else printf("%lld\n",d[a][b]); } } }