1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<queue> 5 #include<stack> 6 #include<iomanip> 7 #include<string> 8 #include<cstring> 9 #include<vector> 10 #include<bitset> 11 #include<algorithm> 12 using namespace std; 13 struct data 14 { 15 int x,y,z; 16 }; 17 data tr[50005]; 18 struct node 19 { 20 int l,w; 21 }; 22 node tt; 23 vector <node> te[10005]; 24 int n,m,a,b,c,q,k=1; 25 int fa[10005],dep[10005],dis[10005][25],f[10005][25]; 26 bool vis[10005]; 27 bool comp(data a,data b) 28 { 29 if (a.z>=b.z) return true; 30 return false; 31 } 32 int find (int x){ 33 if (fa[x]==x) return x; 34 else { 35 fa[x]=find(fa[x]); 36 return fa[x]; 37 } 38 } 39 void kruskal(){ 40 for (int i=1;i<=m;i++) 41 { 42 int r1=find(tr[i].x); 43 int r2=find(tr[i].y); 44 if (r2!=r1){ 45 fa[r2]=r1;//here 46 tt.l=tr[i].y;tt.w=tr[i].z; 47 te[tr[i].x].push_back(tt); 48 tt.l=tr[i].x;tt.w=tr[i].z; 49 te[tr[i].y].push_back(tt); 50 } 51 } 52 } 53 void dfs(int x) 54 { 55 vis[x]=true; 56 for (int i=0;i<te[x].size();i++) 57 if (!vis[te[x][i].l]) 58 { 59 dep[te[x][i].l]=dep[x]+1; 60 dis[te[x][i].l][0]=te[x][i].w; 61 f[te[x][i].l][0]=x; 62 dfs(te[x][i].l); 63 } 64 } 65 void init() 66 { 67 for (int j=1;(1<<j)<=n;j++) 68 for(int i=1;i<=n;i++) 69 { 70 f[i][j]=f[f[i][j-1]][j-1]; 71 dis[i][j]=min(dis[f[i][j-1]][j-1],dis[i][j-1]); 72 } 73 } 74 int lca(int x,int y) 75 { 76 int sm=10000000; 77 if (dep[x]>dep[y]) swap(x,y); 78 int h=dep[y]-dep[x]; 79 for (int i=0;(1<<i)<=h;i++) 80 if ((1<<i)&h) 81 { 82 sm=min(sm,dis[y][i]); 83 y=f[y][i]; 84 } 85 86 if (x!=y) 87 { 88 for (int i=(int)log2(n);i>=0;i--) 89 if (f[x][i]!=f[y][i]) 90 { 91 sm=min(sm,min(dis[x][i],dis[y][i])); 92 x=f[x][i];y=f[y][i]; 93 } 94 sm=min(sm,min(dis[x][0],dis[y][0])); 95 x=f[x][0]; 96 } 97 return sm; 98 } 99 int main() 100 { 101 freopen ("truck.in","r",stdin); 102 //freopen ("truck.out","w",stdout); 103 scanf ("%d%d",&n,&m); 104 for (int i=1;i<=n;i++) fa[i]=i; 105 for (int i=1;i<=m;i++) 106 { 107 scanf ("%d%d%d",&a,&b,&c); 108 tr[i].x=a; 109 tr[i].y=b; 110 tr[i].z=c; 111 } 112 sort(tr+1,tr+m+1,comp); 113 kruskal(); 114 dep[1]=1; 115 dfs(1); 116 init(); 117 scanf ("%d",&q); 118 for (int i=1;i<=q;i++) 119 { 120 scanf ("%d%d",&a,&b); 121 if (find(a)!=find(b)) printf ("-1\n"); 122 else 123 { 124 int s=lca(a,b); 125 printf ("%d\n",s); 126 } 127 } 128 return 0; 129 }
时间: 2024-11-04 21:13:21