543D - Road Improvement - CodeForces Solution


dp trees *2300

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>

using namespace std;

const int N = 2e5 + 100, MOD = 1e9 + 7;

int cnt[N], ans[N], l[N], r[N], res[N];
vector<int> adj[N];
int n;

int mul(int a, int b) {
    return 1LL * a * b % MOD;
}

int sum(int a, int b) {
    a += b;
    if (a >= MOD)
	a -= MOD;
    return a;
}

void dfs(int v) {
    cnt[v] = 1;
    for (auto u : adj[v]) {
	dfs(u);
	cnt[v] = mul(cnt[v], cnt[u] + 1);
    }
}

void DFS(int v, int num) {
    ans[v] = cnt[v];
    int sz = adj[v].size();
    l[0] = r[sz] = 1;
    for (int i = 1, j = sz - 1; i <= sz; i++, j--) {
	l[i] = mul(cnt[adj[v][i - 1]] + 1, l[i - 1]);
	r[j] = mul(cnt[adj[v][j]] + 1, r[j + 1]);
    }
    for (int i = 0; i < sz; i++)
	res[adj[v][i]] = mul(l[i], r[i + 1]);
    for (int i = 0; i < sz; i++) {
	int u = adj[v][i];
	int tmp = mul(num, res[u]) + 1;
	cnt[u] = mul(cnt[u], tmp);
	DFS(u, tmp);
    }
}

int main() {
    ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n;
    for (int i = 1; i < n; i++) {
	int p;
	cin >> p;
	adj[--p].push_back(i);
    }
    dfs(0);
    DFS(0, 1);
    for (int i = 0; i < n; i++)
	cout << ans[i] << " ";
}


Comments

Submit
0 Comments
More Questions

1279A - New Year Garland
1279B - Verse For Santa
202A - LLPS
978A - Remove Duplicates
1304A - Two Rabbits
225A - Dice Tower
1660D - Maximum Product Strikes Back
1513A - Array and Peaks
1251B - Binary Palindromes
768B - Code For 1
363B - Fence
991B - Getting an A
246A - Buggy Sorting
884A - Book Reading
1180A - Alex and a Rhombus
445A - DZY Loves Chessboard
1372A - Omkar and Completion
159D - Palindrome pairs
981B - Businessmen Problems
1668A - Direction Change
1667B - Optimal Partition
1668B - Social Distance
88B - Keyboard
580B - Kefa and Company
960A - Check the string
1220A - Cards
897A - Scarborough Fair
1433B - Yet Another Bookshelf
1283B - Candies Division
1451B - Non-Substring Subsequence