题解:AT_abc207_f [ABC207F] Tree Patrolling

· · 题解

传送门

题解

考虑树上 dp,定义 dp_{i,j,0/1/2} 表示在 i 的子树有 j 个节点被保护,i 没被保护/被保护/放置一个保安的方案数。

初始化为 dp_{u,0,0} 和 dp_{u,1,2} 为 1。

在 dfs 之后,枚举 i 表示当前 u 的子树有 i 个节点被保护。现在需合并 v 的信息,所以为书上背包,其中 v 为 u 的一个儿子。

再枚举 j 表示当前 v 的子树有 j 个节点被保护。

现在看 u 和 v 第三维不同的值会得出什么的结果呢。

v \ u 0 1 2
0 0 1 2
1 0 1 2
2 1 1 2

有以下转移式。

有点长。

其中 t0 为未改动的 dp_{u,i,0},t1 为未改动的 dp_{u,i,1},t2 为未改动的 dp_{u,i,2},因为转移过程中 dp_{u,i,0} 和 dp_{u,i,1} 和 dp_{u,i,2} 可能会被修改,答案可能变大。

最后,对于每个 k,答案为 dp_{root,k,0}+dp_{root,k,1}+dp_{root,k,2},其中 root 为你所定的根。

AC code:

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int p=1e9+7;
const int N=2e3+5;
int n;
int add(int x,int y){
    ll res=1ll*x+y;
    if(res>=p){
        res-=p;
    }
    return res;
}
int mul(int x,int y){
    ll res=1ll*x*y;
    if(res>=p){
        res%=p;
    }
    return res;
}
vector<int> g[N];
int sz[N];
int dp[N][N][3];//dp[i][j][0/1/2] 表示在 i 的子树被保护的节点为 j 个,为没被保护/被保护/自力更生。
void dfs(int u,int f){
    dp[u][0][0]=dp[u][1][2]=sz[u]=1;
    for(int v:g[u]){
        if(v!=f){
            dfs(v,u);
            for(int i=sz[u];i>=0;i--){
                int t0=dp[u][i][0],t1=dp[u][i][1],t2=dp[u][i][2];
                dp[u][i][0]=dp[u][i][1]=dp[u][i][2]=0;
                for(int j=sz[v];j>=0;j--){
                    dp[u][i+j][0]=add(dp[u][i+j][0],mul(t0,dp[v][j][0]));
                    dp[u][i+j][0]=add(dp[u][i+j][0],mul(t0,dp[v][j][1]));
                    dp[u][i+j+1][1]=add(dp[u][i+j+1][1],mul(t0,dp[v][j][2]));//u 被保护了。 
                    dp[u][i+j][1]=add(dp[u][i+j][1],mul(t1,dp[v][j][0]));
                    dp[u][i+j][1]=add(dp[u][i+j][1],mul(t1,dp[v][j][1]));
                    dp[u][i+j][1]=add(dp[u][i+j][1],mul(t1,dp[v][j][2]));
                    dp[u][i+j+1][2]=add(dp[u][i+j+1][2],mul(t2,dp[v][j][0]));//v 被保护了。
                    dp[u][i+j][2]=add(dp[u][i+j][2],mul(t2,dp[v][j][1]));
                    dp[u][i+j][2]=add(dp[u][i+j][2],mul(t2,dp[v][j][2]));
                }
            }
            sz[u]+=sz[v];
        }
    }
} 
signed main(){
    //HAPPY!
    ios_base::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin>>n;
    for(int i=1;i<n;i++){
        int x,y;
        cin>>x>>y;
        g[x].push_back(y),g[y].push_back(x);
    }
    dfs(1,0);
    for(int i=0;i<=n;i++){
        int ans=add(dp[1][i][0],add(dp[1][i][1],dp[1][i][2]));
        cout<<ans<<"\n";
    }
    return 0;
}