比赛 |
中秋节快乐! |
评测结果 |
AAAAAAAAAAAAAAAAAAAA |
题目名称 |
货车运输 |
最终得分 |
100 |
用户昵称 |
flyfree |
运行时间 |
1.667 s |
代码语言 |
C++ |
内存使用 |
4.79 MiB |
提交时间 |
2024-09-17 08:17:15 |
显示代码纯文本
#include<bits/stdc++.h>
using namespace std;
#define MAXN 100010
int m,n,idx,q;
int f[MAXN],used[MAXN];
int hd[MAXN],nxt[MAXN],val[MAXN],ed[MAXN];
int dep[MAXN],lca[MAXN][30],lca_val[MAXN][30];
struct node{
int l,r,w;
}line[MAXN];
bool cmp(node a,node b){
return a.w>b.w;
}
int find(int x){
// cout<<x<<" "<<f[x]<<endl;
if(f[x]==x)return x;
else return f[x]=find(f[x]);
}
void build(int x,int y,int z){
nxt[++idx]=hd[x];
hd[x]=idx;
ed[idx]=y;
val[idx]=z;
}
void dfs(int num,int h,int p,int p_val){
// cout<<num<<" "<<h<<" "<<p<<" "<<p_val<<endl;
dep[num]=h;
lca[num][0]=p,lca_val[num][0]=p_val;
for(int i=1;i<=15;i++){
lca[num][i]=lca[lca[num][i-1]][i-1];
lca_val[num][i]=min(lca_val[lca[num][i-1]][i-1],lca_val[num][i-1]);
// cout<<num<<" "<<i<<" "<<lca[num][i]<<" "<<lca_val[num][i]<<endl;
}
for(int i=hd[num];i;i=nxt[i]){
int y=ed[i];
if(y!=p){
dfs(y,h+1,num,val[i]);
}
}
}
int get_val(int x,int y){
int val_x=1e9,val_y=1e9;
if(dep[x]<dep[y])swap(x,y);
for(int i=15;i>=0;i--){
// cout<<"1 "<<x<<" "<<y<<" "<<val_x<<" "<<val_y<<" "<<lca_val[x][i]<<endl;
if(dep[lca[x][i]]>=dep[y]){
val_x=min(val_x,lca_val[x][i]);
x=lca[x][i];
}
if(dep[x]==dep[y])break;
}
// cout<<val_x<<" "<<val_y<<endl;
if(x==y)return min(val_x,val_y);
for(int i=15;i>=0;i--){
// cout<<"2 "<<x<<" "<<y<<endl;
if(lca[x][i]!=lca[y][i]){
val_x=min(val_x,lca_val[x][i]);
val_y=min(val_y,lca_val[y][i]);
y=lca[y][i];
x=lca[x][i];
}
}
val_x=min(val_x,lca_val[x][0]);
val_y=min(val_y,lca_val[y][0]);
return min(val_x,val_y);
}
int main(){
freopen("truck.in","r",stdin);
freopen("truck.out","w",stdout);
cin>>n>>m;
for(int i=1;i<=m;i++){
cin>>line[i].l>>line[i].r>>line[i].w;
}
for(int i=1;i<=n;i++)f[i]=i;
sort(line+1,line+1+m,cmp);
for(int i=1;i<=m;i++){
int l=line[i].l,r=line[i].r,w=line[i].w;
if(find(l)!=find(r)){
f[find(l)]=f[find(r)];
build(l,r,w);
build(r,l,w);
}
}
for(int i=1;i<=n;i++){
if(!used[find(i)]){
used[find(i)]=1;
dfs(find(i),1,0,0);
}
}
cin>>q;
for(int i=1;i<=q;i++){
int x,y;
cin>>x>>y;
if(find(x)!=find(y))cout<<"-1\n";
else cout<<get_val(x,y)<<endl;
}
return 0;
}