AcWing352. 闇の連鎖

//https://www.acwing.com/problem/content/description/354/
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10,M=2*N;
int e[M],ne[M],h[N],idx;
int depth[N],fa[N][20];
int q[N];
int d[N];
int ans;
int n,m;
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[root]=1,depth[0]=0;
    int hh=0,tt=0;
    q[tt++]=root;
    while(hh<tt){
        int u=q[hh++];
        for(int i=h[u];~i;i=ne[i]){
            int j=e[i];
            if(depth[j]>depth[u]+1){
                depth[j]=depth[u]+1;
                q[tt++]=j;
                fa[j][0]=u;
                for(int k=1;k<=17;k++) fa[j][k]=fa[fa[j][k-1]][k-1];
            }
        }
    }
}
int lca(int a,int b){
    if(depth[a]<depth[b]) swap(a,b);
    for(int k=17;k>=0;k--){
        if(depth[fa[a][k]]>=depth[b]) a=fa[a][k];
    }
    if(a==b) return a;
    for(int k=17;k>=0;k--){
        if(fa[a][k]!=fa[b][k]){
            a=fa[a][k],b=fa[b][k];
        }
    }
    return fa[a][0];
}
int dfs(int u,int fa){
    int res=d[u];
    for(int i=h[u];~i;i=ne[i]){
        int j=e[i];
        if(fa!=j){
            int s=dfs(j,u);
            if(s==0) ans+=m;
            else if(s==1) ans++;
            res+=s;
        }
    }
    return res;
}
int main(){
    scanf("%d%d",&n,&m);
    memset(h,-1,sizeof h);
    for(int i=0,a,b;i<n-1;i++){
        scanf("%d%d",&a,&b);
        add(a,b),add(b,a);
    }
    bfs(1);
    for(int i=0,a,b;i<m;i++){
        scanf("%d%d",&a,&b);
        d[a]++,d[b]++,d[lca(a,b)]-=2;
    }
    dfs(1,-1);
    printf("%d\n",ans);
    return 0;
}
posted @ 2025-05-05 12:02  九三青梧  阅读(6)  评论(0)    收藏  举报