diff --git a/src/9/2/P1967.cpp b/src/9/2/P1967.cpp index 21ae23b..0a13100 100644 --- a/src/9/2/P1967.cpp +++ b/src/9/2/P1967.cpp @@ -1,9 +1,11 @@ +#include #include #include #include #include #include #include +#include #include using ll = int64_t; @@ -23,9 +25,11 @@ struct XYZ{ } }; -ll n,m; +const ll maxlog = 15, inf=1e9; +ll n,m,q; std::vector> edg; -std::vector unf; +std::vector unf, dpth; +std::vector> fth,cost; std::priority_queue pq; ll mergednum = 0; @@ -42,6 +46,42 @@ static inline bool ismerged(ll a,ll b){ return find(a)==find(b); } +static inline void dfs(ll f,ll cur){ + dpth[cur]=dpth[f]+1; + fth[cur][0]=f; + for(ll i=1;i<=maxlog;i++){ + fth[cur][i]=fth[fth[cur][i-1]][i-1]; + cost[cur][i]=std::min(cost[fth[cur][i-1]][i-1],cost[cur][i-1]); + } + for(auto nxt:edg[cur]){ + if(nxt.to==f)continue; + cost[nxt.to][0]=nxt.w; + dfs(cur,nxt.to); + } +} + +static inline ll lca(ll a,ll b){ + if(dpth[a]>dpth[b])std::swap(a,b); + // ll tmp = dpth[b]-dpth[1],ans=0;错误 + ll tmp = dpth[b]-dpth[a],ans=inf; + for(ll j=0;tmp;j++,tmp>>=1){ + if(tmp&1){ + ans=std::min(ans,cost[b][j]); + b=fth[b][j]; // 注意在if里面 + } + } + if(a==b)return ans; + for(ll j=maxlog;j>=0 && a!=b;j--){ + if(fth[a][j]!=fth[b][j]){ + ans=std::min({ans,cost[a][j],cost[b][j]}); + a=fth[a][j]; + b=fth[b][j]; + } + } + ans=std::min({ans,cost[a][0],cost[b][0]}); + return ans; +} + int main(){ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); @@ -50,8 +90,15 @@ int main(){ edg.resize(n+1); unf.resize(n+1); + fth.resize(n+1,std::vector(maxlog+1)); + cost.resize(n+1,std::vector(maxlog+1,inf)); + dpth.resize(n+1); for(ll i=1;i<=n;i++){ + unf[i]=i; + } + + for(ll i=1;i<=m;i++){ ll x,y,z; std::cin>>x>>y>>z; pq.emplace(x,y,z); @@ -67,12 +114,26 @@ int main(){ mergednum++; } - for(ll u=1;u<=n;u++){ - for(auto [v,w]:edg[u]){ - char buff[128]; - memset(buff, 0, sizeof(buff)); - sprintf(buff,"point %lld to %lld weight %lld\n",u,v,w); - std::cout<>q; + for(ll i=1;i<=q;i++){ + ll a,b; + std::cin>>a>>b; + if (!ismerged(a, b)) { + std::cout<<"-1\n"; + continue; + } + std::cout<