Codeforces Round #196 (Div. 2) D. Book of Evil 树形dp
题目链接:
http://codeforces.com/problemset/problem/337/D
D. Book of Evil
memory limit per test256 megabytes
样例输出
3
题意
给你一颗树,边长都为1,魔鬼会在某个点释放魔法,魔法的影响范围是d现在告诉你,若干个被影响的城市,叫你求魔鬼可能在的顶点数量。
题解
树dp维护一个点到最远的被影响城市的距离。类似直径一样转移。
代码
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<ctime>
#include<vector>
#include<cstdio>
#include<string>
#include<bitset>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define sz() size()
#define pb(v) push_back(v)
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)
#define scf scanf
#define prf printf
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;
const int INF=0x3f3f3f3f;
const LL INFL=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-8;
const double PI = acos(-1.0);
//start----------------------------------------------------------------------
const int maxn=101010;
VI G[maxn];
int n,m,d;
int dp[maxn][2],id[maxn];
bool arr[maxn];
///dp[u][0]:最大值,dp[u][1]:次大值
void dfs(int u,int fa){
dp[u][0]=dp[u][1]=-INF;
if(arr[u]) dp[u][0]=dp[u][1]=0;
id[u]=-1;
rep(i,0,G[u].sz()){
int v=G[u][i];
if(v==fa) continue;
dfs(v,u);
if(dp[v][0]<0) continue;
if(dp[u][0]<dp[v][0]+1){
dp[u][1]=dp[u][0];
dp[u][0]=dp[v][0]+1;
id[u]=v;
}else if(dp[u][1]<dp[v][0]+1){
dp[u][1]=dp[v][0]+1;
}
}
}
void dfs2(int u,int fa,int ma){
dp[u][0]=max(dp[u][0],ma);
rep(i,0,G[u].sz()){
int v=G[u][i];
if(v==fa) continue;
if(id[u]==v){
dfs2(v,u,max(dp[u][1],ma)+1);
}else{
dfs2(v,u,max(dp[u][0],ma)+1);
}
}
}
int main() {
clr(arr,0);
scf("%d%d%d",&n,&m,&d);
rep(i,0,m){
int x; scf("%d",&x);
arr[x]=1;
}
rep(i,0,n-1){
int u,v;
scf("%d%d",&u,&v);
G[u].pb(v);
G[v].pb(u);
}
dfs(1,-1);
dfs2(1,-1,-INF);
int cnt=0;
for(int i=1;i<=n;i++) if(dp[i][0]<=d) cnt++;
prf("%d\n",cnt);
return 0;
}
//end-----------------------------------------------------------------------