传送门:【CodeForces】461B Appleman and Tree
题目分析:
自己不会做啊= = 想不到。。
首先按照题目意思建一颗树。
接下来我们用dp[ u ][ 0 ]表示u为白色时将u的子树中包含黑点的子树都删除的方案数(u为黑色时dp[ u ][ 0 ] = 0),用dp[ u ][ 1 ]表示以u为根结点处理完节点u后的方案总数。答案即dp[ 0 ][ 1 ]。
对于节点u,如果u为黑色,那么显然子树中包含黑色的子树都要删除,如果不为黑色,那么子树中可以保留一棵含黑色的子树。
很显然,如果要删除子树v,那么方案数为dp[ v ][ 0 ] + dp[ v ][ 1 ],因为要么删除v的含黑色的子树,要么删除边u-v。
反正我是无力了,自己理解的依旧不够深刻,能看懂多少算多少吧。。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
#define REP( i , a , b ) for ( int i = ( a ) ; i < ( b ) ; ++ i )
#define FOR( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define REV( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define travel( e , H , u ) for ( Edge* e = H[u] ; e ; e = e -> next )
#define CLR( a , x ) memset ( a , x , sizeof a )
typedef long long LL ;
const int MAXN = 100005 ;
const int MAXE = 200005 ;
const int mod = 1e9 + 7 ;
struct Edge {
int v ;
Edge* next ;
} E[MAXE] , *H[MAXN] , *cur ;
int color[MAXN] ;
LL dp[MAXN][2] ;
void clear () {
cur = E ;
CLR ( H , 0 ) ;
CLR ( color , 0 ) ;
CLR ( dp , 0 ) ;
}
void addedge ( int u , int v ) {
cur -> v = v ;
cur -> next = H[u] ;
H[u] = cur ++ ;
}
void scanf ( int& x , char c = 0 ) {
while ( ( c = getchar () ) < '0' || c > '9' ) ;
x = c - '0' ;
while ( ( c = getchar () ) >= '0' && c <= '9' ) x = x * 10 + c - '0' ;
}
void dfs ( int u , int f = 0 ) {
dp[u][color[u]] = 1 ;
travel ( e , H , u ) {
int v = e -> v ;
if ( v == f ) continue ;
dfs ( v , u ) ;
dp[u][1] = dp[u][1] * ( dp[v][0] + dp[v][1] ) % mod ;//删除v
dp[u][1] = ( dp[u][1] + dp[u][0] * dp[v][1] ) % mod ;//u为白时保留一棵含黑点的子树
dp[u][0] = dp[u][0] * ( dp[v][0] + dp[v][1] ) % mod ;//u为白时删除v
}
}
void solve () {
int n , x ;
while ( ~scanf ( "%d" , &n ) ) {
clear () ;
REP ( i , 1 , n ) {
scanf ( x ) ;
addedge ( x , i ) ;
addedge ( i , x ) ;
}
REP ( i , 0 , n ) scanf ( color[i] ) ;
dfs ( 0 ) ;
printf ( "%I64d\n" , dp[0][1] ) ;
}
}
int main () {
solve () ;
return 0 ;
}