1 solutions

  • 1
    @ 2025-9-12 10:52:53

    洛谷绿题太过分了,完全就是LCA模板。

    #include<iostream>
    #include<cstdio>
    using namespace std;
    const int NR=30001,R=16;
    int cnt,hed[NR],dep[NR],nxt[2*NR],to[2*NR],f[NR][R];
    void ad(int u,int v)
    {
    	cnt++;
    	to[cnt]=v;
    	nxt[cnt]=hed[u];
    	hed[u]=cnt;
    	return;
    }
    void dfs(int x,int fa)
    {
    	dep[x]=dep[fa]+1;
    	f[x][0]=fa;
    	int i;
    	for(i=1;i<R;i++) f[x][i]=f[f[x][i-1]][i-1];
    	for(i=hed[x];i;i=nxt[i])
    		if(to[i]!=fa) dfs(to[i],x);
    	return;
    }
    int lca(int x,int y)
    {
    	if(dep[x]<dep[y]) swap(x,y);
    	int i;
    	for(i=R-1;i>=0;i--)
    		if(dep[x]-dep[y]>=(1<<i)) x=f[x][i];
    	if(x==y) return x;
    	for(i=R-1;i>=0;i--)
    		if(f[x][i]!=f[y][i])
    		{
    			x=f[x][i];
    			y=f[y][i];
    		}
    	return f[x][0];
    }
    int main()
    {
    	int n,m,i,x,ans=0;
    	cin>>n;
    	for(i=1;i<n;i++)
    	{
    		int a,b;
    		cin>>a>>b;
    		ad(a,b);
    		ad(b,a);
    	}
    	dfs(1,0);
    	cin>>m>>x;
    	m--;
    	while(m--)
    	{
    		int y;
    		cin>>y;
    		ans+=dep[x]+dep[y]-2*dep[lca(x,y)];
    		x=y;
    	}
    	cout<<ans;
    	return 0;
    }
    
    • 1

    Information

    ID
    8053
    Time
    100ms
    Memory
    128MiB
    Difficulty
    4
    Tags
    # Submissions
    2
    Accepted
    2
    Uploaded By