dfs序lca求条
  • 板块灌水区
  • 楼主Chtholly__Nota
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/11/26 22:48
  • 上次更新2024/11/27 13:15:24
查看原帖
dfs序lca求条
847559
Chtholly__Nota楼主2024/11/26 22:48
#include<bits/stdc++.h>
/*
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#include<ext/pb_ds/hash_policy.hpp>
#include<ext/pb_ds/trie_policy.hpp>
#include<ext/pb_ds/priority_queue.hpp>
#include<ext/rope>
using namespace __gnu_cxx;
using namespace __gnu_pbds;
ด้้้้้็้้้็็็็็้้้้้็็็็็้้้้้้็็็็็้้้้้็็็็็้้้้้้็็็็็้้้้้็็็็็้้้้้้็็็็็้้้้้็็็็็้้้้้้็็
*/
#define pn putchar('\n')
#define ps putchar(' ')
using namespace std;
typedef long long ll;

template <typename T> void re(T &t) {
	t=0; char ch=getchar(); int f=1;
	while (ch<'0'||ch>'9') { if (ch=='-') f=-1; ch=getchar(); }
	do { (t=((t<<3)+(t<<1)))+=ch-'0'; ch=getchar(); } while ('0'<=ch&&ch<='9'); t*=f;
}

inline void wr(int x){
    if(x<0) putchar('-'),x=-x;
    if(x>9) wr(x/10);
    putchar(x%10+'0');
}

int lg[500005],dfn[500005];
int f[500005][21];
int n,m,s,cnt;
int l,r,xx,u,v;
vector<int> g[500005];

void dfs(int p,int fa){
    f[dfn[p]=++cnt][0]=fa;
    for(int i:g[p]) if(i!=fa) dfs(i,p);
}

int lca(int u,int v){
    if(u==v) return u;
    if((u=dfn[u])>(v=dfn[v])) swap(u,v);
    int d=lg[v-u++];
    return min(dfn[f[u][d]],dfn[f[v-(1<<d)+1][d]]);
}

int main() {
    re(n),re(m),re(s);
    for(int i=1;i<n;i++){
        re(u),re(v);
        g[u].push_back(v);
        g[v].push_back(u);
    }
    lg[1]=0;
    for(int i=2;i<=(n<<1)-1;i++) lg[i]=lg[i>>1]+1;
    dfs(s,0);
    for(int j=1;j<=lg[n];j++){
        for(int i=1;i<=n-(1<<j)+1;i++){
            f[i][j]=min(dfn[f[i][j-1]],dfn[f[i+(1<<(j-1))][j-1]]);
        }
    }
    while(m--){
        re(u),re(v);
        wr(lca(u,v)),pn;
    }
	return 0;
}


















//ด้้้้้็้้้็็็็็้้้้้็็็็็้้้้้้็็็็็้้้้้็็็็็้้้้้้็็็็็้้้้้็็็็็้้้้้้็็็็็้้้้้็็็็็้้้้้้็็
2024/11/26 22:48
加载中...