#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int mod = 1e9 + 7;
struct mint {
int v = 0;
mint() {}
mint(int x) {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<mint, 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;
d[i] %= mod;
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;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
1 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
37 ms |
3668 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
37 ms |
3668 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
1 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |