P11967 [GESP202503 八级] 割裂

//https://www.luogu.com.cn/problem/P11967
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10,M=N*2;
int e[M],ne[M],h[N],idx;
int depth[N],fa[N][25];
int q[N];
int n,a;
int d[N];
inline int read(){
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*f;
}
void write(int x){
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
void add(int a,int b){
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void bfs(int root){
    memset(depth,0x3f,sizeof depth);
    depth[0]=0,depth[root]=1;
    int hh=0,tt=1;
    q[0]=root;
    while(hh<tt){
        int u=q[hh++];
        for(int i=h[u];~i;i=ne[i]){
            int v=e[i];
            if(depth[v]>depth[u]+1){
                depth[v]=depth[u]+1;
                q[tt++]=v;
                fa[v][0]=u;
                for(int k=1;k<=20;k++) fa[v][k]=fa[fa[v][k-1]][k-1];
            }
        }
    }
}
void dfs(int u,int father){
    for(int i=h[u];~i;i=ne[i]){
        int j=e[i];
        if(j!=father){
            dfs(j,u);
            d[u]+=d[j];
        }
    }
}
int lca(int a,int b){
    if(depth[a]<depth[b]) swap(a,b);
    for(int k=20;k>=0;k--) if(depth[fa[a][k]]>=depth[b]) a=fa[a][k];
    if(a==b) return a;
    for(int k=20;k>=0;k--){
        if(fa[a][k]!=fa[b][k]){
            a=fa[a][k],b=fa[b][k];
        }
    }
    return fa[a][0];
}
int main(){
	memset(h,-1,sizeof h);
	n=read(),a=read();
	for(int i=0,u,v;i<n-1;i++){
		u=read(),v=read();
		add(u,v),add(v,u);
	}
	bfs(1);
	for(int i=0,u,v;i<a;i++){
		u=read(),v=read();
		int p=lca(u,v);
		d[u]++,d[v]++;
		d[p]--;
		if(fa[p][0]) d[fa[p][0]]--;
	}
	dfs(1,-1);
	int u=read(),v=read(),cnt=0;
	int p=lca(u,v);
	while(u!=p){
		if(d[u]==0) cnt++;
		u=fa[u][0];
	}
	while(v!=p){
		if(d[v]==0) cnt++;
		v=fa[v][0];
	}
	if(d[u]==0) cnt++;
	write(cnt);
	return 0;
}
posted @ 2025-05-10 10:42  九三青梧  阅读(11)  评论(0)    收藏  举报