1. 程式人生 > >Codeforces Round #302 (Div. 1) D - Road Improvement 樹形dp

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

div rst problem c++ define using improve fine code

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