Of course, this question has a lot of practice, but I saw no one was surprised to write the DSU
According to experience two-way side do not even question before, this problem can be disjoint-set maintenance Unicom
Then for each ask \ (the X-, the y-\) , consider merging heuristics
When the two set points \ (x, y \) merging, some of which related to the query point may be solved, traverses \ (x, y \) query is actually set in the equivalent, it can be used directly inspired type merger inquiry able to save this set of points involved in the merger when we have to traverse the array, it can be done for the answer to the question at the same time
typedef long long ll;
#define rep(i,a,b) for(int i=a,i##end=b;i<=i##end;++i)
#define drep(i,a,b) for(int i=a,i##end=b;i>=i##end;--i)
char IO;
int rd(){
int s=0,f=0;
while(!isdigit(IO=getchar())) if(IO=='-') f=1;
do s=(s<<1)+(s<<3)+(IO^'0');
while(isdigit(IO=getchar()));
return f?-s:s;
}
const int N=1e5+10;
int n,m,q;
struct Edge{
int u,v,x;
void Get(){ u=rd(),v=rd(),x=rd(); }
bool operator < (const Edge __) const {
return x>__.x;
}
}e[N];
int ans[N];
struct Query{
int x,id;
};
vector <Query> V[N];
int fa[N];
int Find(int x){ return fa[x]==x?x:fa[x]=Find(fa[x]);}
int main(){
n=rd(),m=rd();
rep(i,1,n) fa[i]=i;
rep(i,1,m) e[i].Get();
sort(e+1,e+m+1);
rep(i,1,q=rd()) {
ans[i]=-1;
int x=rd(),y=rd();
V[x].push_back((Query){y,i});
V[y].push_back((Query){x,i});
}
rep(i,1,m) {
int x=Find(e[i].u),y=Find(e[i].v);
if(x==y) continue;
if(V[x].size()>V[y].size()) swap(x,y);
fa[x]=y;
rep(j,0,V[x].size()-1) {
int t=V[x][j].x,id=V[x][j].id;
if(Find(t)==y) {
ans[id]=max(ans[id],e[i].x);
} else V[y].push_back(V[x][j]);
}
}
rep(i,1,q) printf("%d\n",ans[i]);
}
Very concise
If you do not understand the principles of heuristic merge, I can prove it simple
The total number of these sets, the elements of m
Every time we would merge into a small set of large above-set size at least twice, so each element will be the most accessible (m) times in the merger log2
Overall complexity \ (q \ cdot log (q ) \)