给出一棵树,给出感染物的感染范围,给出一些已经确定被感染的点,问感染物可能放置的点的个数。
#include <iostream>
# include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#define MAX 100007
#define INF (-(1<<29));
using namespace std;
int n,m,d;
int dp[MAX];
int dd[MAX];
int mark[MAX];
int lef[MAX],rig[MAX];
vector<int> e[MAX];
void add ( int u , int v )
{
e[u].push_back ( v );
e[v].push_back ( u );
}
void dfs ( int u , int p )
{
if ( mark[u] ) dp[u] = 0;
else dp[u] = INF;
for ( int i = 0 ; i < e[u].size() ; i++ )
{
int v = e[u][i];
if ( v == p ) continue;
dfs ( v , u );
dp[u] = max ( dp[u] , dp[v] + 1 );
}
}
void dfs1 ( int u , int p )
{
lef[0] = INF;
rig[e[u].size()+1] = INF;
for ( int i = 0 ; i < e[u].size() ; i++ )
{
int x = i+1;
int v = e[u][i];
if ( v == p )
{
lef[x] = lef[x-1];
continue;
}
lef[x] = max ( lef[x-1] , dp[v] );
}
for ( int i = e[u].size()-1 ; i >= 0 ; i-- )
{
int x = i+1;
int v = e[u][i];
if ( v == p )
{
rig[x] = rig[x+1];
continue;
}
rig[x] = max ( rig[x+1] , dp[v] );
}
for ( int i = 0 ; i < e[u].size() ; i++ )
{
int v = e[u][i];
if ( v == p ) continue;
dd[v] = max ( dd[u] , max ( lef[i], rig[i+2])+1 )+1;
dp[v] = max ( dp[v] , dd[v] );
}
for ( int i = 0 ; i < e[u].size() ; i++ )
{
int v = e[u][i];
if ( v == p ) continue;
dfs1 ( v , u );
}
}
void Clear ()
{
for ( int i = 0 ; i < MAX ; i++ )
e[i].clear();
}
int main ( )
{
while ( ~scanf ( "%d%d%d" , &n , &m, &d ) )
{
int x,y;
Clear();
memset ( mark , 0 , sizeof ( mark ) );
memset ( dd , -0x3f , sizeof ( dd ) );
for ( int i = 0 ; i < m ; i++ )
{
scanf ( "%d" , &x );
mark[x] = 1;
}
for ( int i = 1 ; i < n ; i++ )
{
scanf ( "%d%d" , &x , &y );
add ( x, y );
}
dfs ( 1 , -1 );
if ( mark[1] ) dd[1] = 0;
else dd[1] = INF;
dfs1 ( 1 , -1 );
int ans = 0;
for ( int i = 1 ; i <= n ; i ++ )
if ( dp[i] <= d && dp[i] >= 0 )
ans++;
printf ( "%d\n" , ans );
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
codeforces 337D D. Book of Evil(树形dp)
原文:http://blog.csdn.net/qq_24451605/article/details/48880549