This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#include<random>
#define ll long long
#define F first
#define S second
#define in insert
#define pb push_back
#define ppb pop_back()
#define d3 ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define cans cout << ans << "\n";
#define yes cout << "Yes" << "\n";
#define no cout << "No" << "\n";
#define pll pair<ll,ll>
#define lin cout << "\n";
#define sqr 340
#define mid ((l+r)/2)
#define lc (2*x)
#define rc (2*x+1)
using namespace std;
const ll N = 100009;
const ll m = 1e9+7;
ll n , q , ans;
ll p[N] , d[N];
ll path[N];
ll dp[N];
vector<ll> adj[N];
multiset<ll> v[N];
void dfs(ll x)
{
path[x]=0;
for(auto it : adj[x])
{
dfs(it);
v[x].in(path[it]+d[it]);
}
if(v[x].size()==0)
dp[x]=0;
else if(v[x].size()==1)
dp[x]=*(--v[x].end());
else
{
auto it = (--v[x].end());
dp[x]=*it;
it--;
dp[x]+=*it;
}
dp[x]%=m;
ans+=dp[x];
ans%=m;
if(v[x].size())
path[x]=*(--v[x].end());
}
int main()
{
d3
cin >> n;
p[0]=-1;
for(int i = 1 ; n>i ; i++)
{
cin >> p[i];
adj[p[i]].pb(i);
}
d[0]=0;
for(int i = 1 ; n>i ; i++)
cin >> d[i];
dfs(0);
cans
cin >> q;
while(q--)
{
ll val , ad;
cin >> val >> ad;
ll pr = val;
ll sum = path[val];
d[val]+=ad;
if(path[p[pr]]==path[pr]+d[pr]-ad)
{
while(p[pr]!=-1)
{
ll np = p[pr];
ans-=dp[np];
ans%=m;
ans+=m;
ans%=m;
sum+=d[pr];
auto it = v[np].find(sum-ad);
v[np].erase(it);
v[np].in(sum);
if(v[np].size()==0)
dp[np]=0;
else if(v[np].size()==1)
dp[np]=*(--v[np].end());
else
{
auto itt = (--v[np].end());
dp[np]=*itt;
itt--;
dp[np]+=*itt;
}
dp[np]%=m;
ans+=dp[np];
ans%=m;
if(v[np].size())
path[np]=*(--v[np].end());
pr=np;
}
}
else
{
ll np = p[pr];
ans-=dp[np];
ans%=m;
ans+=m;
ans%=m;
auto it = v[np].find(path[pr]+d[pr]-ad);
v[np].erase(it);
v[np].in(path[pr]+d[pr]);
if(v[np].size()==0)
dp[np]=0;
else if(v[np].size()==1)
dp[np]=*(--v[np].end());
else
{
auto itt = (--v[np].end());
dp[np]=*itt;
itt--;
dp[np]+=*itt;
}
dp[np]%=m;
ans+=dp[np];
ans%=m;
if(v[np].size())
path[np]=*(--v[np].end());
}
cans
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |