#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int mod = 1e9 + 7;
struct mint {
int v = 0;
mint() {}
mint(ll x) {
if (x >= mod) {
v = x % mod;
} else {
v = x;
}
}
mint& operator+=(mint b) {
if ((v += b.v) >= mod) {
v -= mod;
}
return *this;
}
mint& operator-=(mint b) {
if ((v -= b.v) < 0) {
v += mod;
}
return *this;
}
friend mint operator+(mint a, mint b) {
return a += b;
}
friend mint operator-(mint a, mint b) {
return a -= b;
}
friend bool operator>(mint a, mint b) {
return a.v > b.v;
}
friend bool operator<(mint a, mint b) {
return b > a;
}
friend ostream& operator<<(ostream &os, mint a) {
return os << a.v;
}
};
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
int n;
cin >> n;
int p[n]{};
for (int i = 1; i < n; i++) {
cin >> p[i];
}
int d[n]{};
for (int i = 1; i < n; i++) {
cin >> d[i];
}
pair<ll, int> dp[n][2];
for (int i = 0; i < n; i++) {
dp[i][0] = dp[i][1] = {0, -1};
}
mint ans = 0;
for (int i = n - 1; i > 0; i--) {
if (dp[i][0].first + d[i] > dp[p[i]][1].first) {
dp[p[i]][1] = {dp[i][0].first + d[i], i};
if (dp[p[i]][1] > dp[p[i]][0]) swap(dp[p[i]][0], dp[p[i]][1]);
}
ans += dp[i][0].first + dp[i][1].first;
}
ans += dp[0][0].first + dp[0][1].first;
cout << (ans.v % mod + mod) % mod << '\n';
int q;
cin >> q;
while (q--) {
int i, v;
cin >> i >> v;
d[i] += v;
mint old = 0, cur = -1;
while (old.v != cur.v && i != 0) {
old = cur = dp[p[i]][0].first;
if (dp[p[i]][0].second == i) {
swap(dp[p[i]][0], dp[p[i]][1]);
}
if (dp[p[i]][1].second == i || dp[i][0].first + d[i] > dp[p[i]][1].first) {
ans -= dp[p[i]][0].first + dp[p[i]][1].first;
dp[p[i]][1] = {dp[i][0].first + d[i], i};
if (dp[p[i]][1] > dp[p[i]][0]) {
swap(dp[p[i]][0], dp[p[i]][1]);
}
cur = dp[p[i]][0].first;
ans += dp[p[i]][0].first + dp[p[i]][1].first;
}
i = p[i];
}
cout << (ans.v % mod + mod) % mod << '\n';
}
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
344 KB |
Output is correct |
2 |
Correct |
3 ms |
348 KB |
Output is correct |
3 |
Correct |
1 ms |
348 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
38 ms |
5132 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1539 ms |
5684 KB |
Output is correct |
2 |
Execution timed out |
5035 ms |
6800 KB |
Time limit exceeded |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
344 KB |
Output is correct |
2 |
Correct |
3 ms |
348 KB |
Output is correct |
3 |
Correct |
1 ms |
348 KB |
Output is correct |
4 |
Incorrect |
38 ms |
5132 KB |
Output isn't correct |
5 |
Halted |
0 ms |
0 KB |
- |