Title

【算法与数据结构实验题】 【树形dp】6.1 小明的果树

#include <bits/stdc++.h>
#define MEM(a,x) memset(a,x,sizeof(a))
#define W(a) while(a)
#define gcd(a,b) __gcd(a,b)
#define pi acos(-1.0)
#define PII pair<int,int>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define ull unsigned long long
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define MAX 1000005
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define lowbit(x) (x&-x)
using namespace std;
ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
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;
}
const int N = 1E5+5,M = 2E5+10;
int h[N],ne[M],e[M],idx;
void add(int a,int b)
{
     e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
int odu[N],mark[N];
int dfs(int u,int fa)
{
	int sum=0;
	for(int i=h[u];~i;i=ne[i])
	{
		int j=e[i];
		if(j==fa) continue; 
        int t=dfs(j,u);
        if(t>0)
           sum+=t+2;
        else if(mark[j]>0)
		   sum+=2;
	}
	return sum;
}
int n,m;
int main()
{
	memset(h,-1,sizeof(h));
	n = read(), m = read();
	for(int i=1;i<=n-1;i++)
	{
		int a = read(),b = read();
		add(a,b);add(b,a);
	}
	for(int i=1;i<=m;i++)
    {
    	int x = read();
    	mark[x]++;
	}
	printf("%d",dfs(1,-1));
    return 0;
}


posted @ 2021-10-14 17:13  BeautifulWater  阅读(243)  评论(0编辑  收藏  举报