本人用 tarjan 求 lca 把这题过了,但是倍增被卡了两天。 测评记录
下面放上code :
#include <bits/stdc++.h>
// #pragma GCC optimize(2)
using namespace std;
// #define int long long
#define endl "\n"
const int M = 1e5 + 10;
const int mod = 1e6 + 7 ;
const int inf = 1e9 ;
struct node {
int l , r , v ;
}eg[M] ;
int n , m , cnt ;
bool vis[M] ;
int f[M] , val[M] , dep[M] , ff[M][22] ;
vector <int> e[M] ;
bool cmp (node a , node b) {
return a.v > b.v ;
}
int fr(int x) {
return f[x] == x ? x : f[x] = fr(f[x]) ;
}
void dfs(int x , int y) {
dep[x] = dep[y] + 1 ;
ff[x][0] = y ;
for(int i = 1 ; (1 << i) <= dep[x] ; i ++ ) {
ff[x][i] = ff[ff[x][i - 1]][i - 1] ;
}
for(auto i : e[x]) {
if(i != y) {
dfs(i , x) ;
}
}
}
int LCA(int x , int y) {
if(dep[x] < dep[y]) swap(x , y) ;
while(dep[x] > dep[y]) {
x = ff[x][__lg(dep[x] - dep[y])] ;
}
if(x == y) return x ;
for(int j = __lg(dep[x]) ; j >= 0 ; j --) {
if(ff[x][j] != ff[y][j]) {
x = ff[x][j] ; y = ff[y][j] ;
}
}
return ff[x][0] ;
}
void kruscal() {
cnt = n ;
for(int i = 1 ; i <= 2*n ; i++ ) f[i] = i ;
sort(eg + 1 , eg + 1 + m , cmp) ;
for(int i = 1 ; i <= m ; i++ ) {
int fx = fr(eg[i].l) , fy = fr(eg[i].r) ;
if(fx != fy) {
val[++cnt] = eg[i].v ;
f[cnt] = f[fx] = f[fy] = cnt ;
e[cnt].push_back(fx) ; e[cnt].push_back(fy) ;
e[fx].push_back(cnt) ; e[fy].push_back(cnt) ;
}
}
for(int i = 1 ; i <= cnt ; i ++ ) {
if(!vis[i]) {
dfs(i , 0) ;
}
}
}
void solve() {
cin >> n >> m ;
for(int i = 1 ; i <= m ; i++ ) {
cin >> eg[i].l >> eg[i].r >> eg[i].v ;
}
kruscal() ;
int q ; cin >> q ;
while (q --) {
int x , y ; cin >> x >> y ;
if(fr(x) != fr(y)) cout << "-1\n" ;
else cout << val[LCA(x , y)] << endl ;
}
}
signed main() {
// freopen("stdin.in" , "r" , stdin) ;
// freopen("stdout.out" , "w" , stdout) ;
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t_ = 1 ;
// cin >> t_ ;
while(t_--) {
solve();
// cout << endl;
}
}