Codeforces Round #302 (Div. 1) D - Road Improvement 树形dp

Posted cjlhy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces Round #302 (Div. 1) D - Road Improvement 树形dp相关的知识,希望对你有一定的参考价值。

D - Road Improvemen

思路:0没有逆元!!!! 不能直接除,要求前缀积和后缀积!!!

#include<bits/stdc++.h>
#define LL long long
#define fi first
#define se second
#define mk make_pair
#define PII pair<int, int>
#define y1 skldjfskldjg
#define y2 skldfjsklejg

using namespace std;

const int N = 2e5 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;

int n;
LL dp[N], ans[N], fdp[N];
vector<int> edge[N];
vector<int> L[N], R[N];

void dfs(int u, int fa) {
    dp[u] = 1;
    LL pre = 1;
    L[u].resize(edge[u].size());
    R[u].resize(edge[u].size());
    for(int i = 0; i < edge[u].size(); i++) {
        int v = edge[u][i];
        L[u][i] = pre;
        if(v == fa) continue;
        dfs(v, u);
        dp[u] = dp[u] * (dp[v] + 1) % mod;
        L[u][i] = L[u][i] * (dp[v] + 1) % mod;
        pre = L[u][i];
    }

    pre = 1;
    for(int i = edge[u].size() - 1; i >= 0; i--) {
        int v = edge[u][i];
        R[u][i] = pre;
        if(v == fa) continue;
        R[u][i] = R[u][i] * (dp[v] + 1) % mod;
        pre = R[u][i];
    }
}

void dfs3(int u, int fa, LL val) {
    ans[u] = dp[u] * (val + 1) % mod;
    for(int i = 0; i < edge[u].size(); i++) {
        int v = edge[u][i];
        if(v == fa) continue;
        LL nxv = 1;
        if(i) nxv = L[u][i - 1];
        if(i + 1 < edge[u].size()) nxv = nxv * R[u][i + 1] % mod;
        dfs3(v, u, nxv * (val + 1) % mod);
    }
}

int main() {
    scanf("%d", &n);
    for(int i = 2; i <= n; i++) {
        int x; scanf("%d", &x);
        edge[i].push_back(x);
        edge[x].push_back(i);
    }
    dfs(1, 0);
    dfs3(1, 0, 0);
    for(int i = 1; i <= n; i++) printf("%lld ", ans[i]);
    return 0;
}

/*
*/

 

以上是关于Codeforces Round #302 (Div. 1) D - Road Improvement 树形dp的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #436 E. Fire(背包dp+输出路径)

[ACM]Codeforces Round #534 (Div. 2)

Codeforces Round #726 (Div. 2) B. Bad Boy(贪心)

Codeforces Global Round 19

Codeforces Educational Codeforces Round 67

Codeforces Round 1132Educational Round 61