396C - On Changing Tree - CodeForces Solution


data structures graphs trees

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 300010;
const int mod = 1000000007;
vector<int>g[maxn];
LL c[2][maxn],val[2];
int n,m,L[maxn],R[maxn],d[maxn],clk;
void update(int i){
    while(i < maxn){
        c[0][i] += val[0];
        c[1][i] += val[1];
        c[0][i] %= mod;
        c[1][i] %= mod;
        i += i&-i;
    }
}
LL query(int i){
    LL sum[2] = {0},dep = d[i];
    i = L[i];
    while(i > 0){
        sum[0] += c[0][i];
        sum[1] += c[1][i];
        sum[0] %= mod;
        sum[1] %= mod;
        i -= i&-i;
    }
    return ((sum[0] - dep*sum[1])%mod + mod)%mod;
}
void dfs(int u,int dep){
    L[u] = ++clk;
    d[u] = dep;
    for(int i = g[u].size()-1; i >= 0; --i)
        dfs(g[u][i],dep+1);
    R[u] = clk;
}
int main(){
    int u,op,x,y,z;
    while(~scanf("%d",&n)){
        for(int i = clk = 0; i <= n; ++i) g[i].clear();
        for(int i = 2; i <= n; ++i){
            scanf("%d",&u);
            g[u].push_back(i);
        }
        dfs(1,0);
        memset(c,0,sizeof c);
        scanf("%d",&m);
        while(m--){
            scanf("%d%d",&op,&x);
            if(op == 1){
                scanf("%d%d",&y,&z);
                val[0] = ((LL)y + (LL)d[x]*z)%mod;
                val[1] = z;
                update(L[x]);
                val[0] = -val[0];
                val[1] = -val[1];
                update(R[x]+1);
            }else printf("%I64d\n",query(x));
        }
    }
    return 0;
}
  		  	 			  		  		 	 				   		


Comments

Submit
0 Comments
More Questions

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
1408B - Arrays Sum
1430A - Number of Apartments
1475A - Odd Divisor
1454B - Unique Bid Auction
978C - Letters
501B - Misha and Changing Handles
1496A - Split it