#include <bits/stdc++.h>
using namespace std;
typedef long long int64;
const int64 mod = 1e9 + 7;
const int maxn = 1e5 + 2;
int64 dp[maxn], down[maxn];
int p[maxn];
map <pair <int, int>, int64> c;
vector <int> ad [maxn];
multiset <int64> ms[maxn];
int n;
void upd (int u) {
ms[u].insert(0);
vector <int64> d;
dp[u] = 0;
for (int v: ad[u]) {
ms[u].insert(*--ms[v].end() + c[{u, v}]);
}
if (ms[u].size() >= 1) dp[u] += *--ms[u].end();
if (ms[u].size() >= 2) dp[u] += *----ms[u].end();
}
void dfs (int u) {
for (int v: ad[u]) {
dfs(v);
}
upd(u);
}
int main() {
cin >> n;
for (int i = 1; i <= n - 1; i++){
int x;
cin >> x;
ad[x].push_back(i);
p[i] = x;
}
for (int i = 1; i <= n - 1; i++){
int x;
cin >> x;
c[{p[i], i}] = x;
}
int q;
cin >> q;
dfs(0);
int64 rs = 0;
for (int i = 0; i < n; i++){
rs = (rs + dp[i]) % mod;
}
cout << rs << "\n";
while (q--) {
int64 x,y;
cin >> x >> y;
int u = x;
while (u) {
down[u] = *--ms[u].end();
u = p[u];
}
u = x;
while (u){
ms[p[u]].erase(ms[p[u]].find(down[u] + c[{p[u], u}]));
rs = (rs - dp[p[u]] + mod) % mod;
dp[p[u]] = 0;
u = p[u];
}
c[{p[x], x}]+=y;
u = x;
while (u) {
ms[p[u]].insert(*--ms[u].end() + c[{p[u], u}]);
if (ms[p[u]].size() >= 1) dp[p[u]] += *--ms[p[u]].end();
if (ms[p[u]].size() >= 2) dp[p[u]] += *----ms[p[u]].end();
rs = (rs + dp[p[u]] + mod) % mod;
u = p[u];
}
// for (int i = 0; i < n; i++){
// cout << i << ": ";
// for (int j: ms[i]) cout << j << " ";
// cout << "\n";
// }
cout << rs << "\n";
}
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
20 ms |
7508 KB |
Output is correct |
2 |
Correct |
56 ms |
7556 KB |
Output is correct |
3 |
Correct |
16 ms |
7548 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
834 ms |
27516 KB |
Output is correct |
2 |
Correct |
1450 ms |
27176 KB |
Output is correct |
3 |
Correct |
1593 ms |
28172 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Execution timed out |
5090 ms |
27392 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
20 ms |
7508 KB |
Output is correct |
2 |
Correct |
56 ms |
7556 KB |
Output is correct |
3 |
Correct |
16 ms |
7548 KB |
Output is correct |
4 |
Correct |
834 ms |
27516 KB |
Output is correct |
5 |
Correct |
1450 ms |
27176 KB |
Output is correct |
6 |
Correct |
1593 ms |
28172 KB |
Output is correct |
7 |
Execution timed out |
5090 ms |
27392 KB |
Time limit exceeded |
8 |
Halted |
0 ms |
0 KB |
- |