#include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5, maxc = 300;
long long dp[maxn][maxc + 1];
vector<int> g[maxn];
int par[maxn], c[maxn];
void print(int v) {
for (int j = 0; j <= maxc; ++j) {
cerr << dp[j] << ' ';
}
cerr << '\n';
}
long long tmp[maxc + 1];
void dfs(int v) {
if (g[v].empty()) {
for (int j = 0; j <= maxc; ++j) {
dp[v][j] = abs(j - c[v]);
}
return;
}
for (const int& u : g[v]) {
dfs(u);
for (int j = 0; j <= maxc; ++j) {
dp[v][j] += dp[u][j];
}
}
// cerr << "v: " << v + 1 << " before:\n";
// print(v);
if (par[v] != -1) {
for (int j = 0; j <= maxc; ++j) {
tmp[j] = 1e18;
}
for (int j1 = 0; j1 <= maxc; ++j1) {
for (int j2 = 0; j2 <= maxc - j1; ++j2) {
tmp[j1 + j2] = min(tmp[j1 + j2], dp[v][j1] + abs(c[v] - j2));
}
}
for (int j = 0; j <= maxc; ++j) {
dp[v][j] = tmp[j];
}
}
// cerr << "v: " << v + 1 << ", val: " << val[v] << ", slope: " << slope[v] << '\n';
// print(v);
}
void solve() {
int n, m;
cin >> n >> m;
par[0] = -1, c[0] = 0;
for (int i = 1; i < n + m; ++i) {
cin >> par[i] >> c[i];
--par[i];
g[par[i]].emplace_back(i);
}
dfs(0);
long long ans = 1e18;
for (int j = 0; j <= maxc; ++j) {
ans = min(ans, dp[0][j]);
}
cout << ans << '\n';
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int T = 1;
cin >> T;
while (T--) {
solve();
cerr << "-----------\n";
cout << "-----------\n";
}
#else
int T = 1;
// cin >> T;
while (T--) {
solve();
}
#endif
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
10588 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
2 ms |
10668 KB |
Output is correct |
2 |
Correct |
3 ms |
10588 KB |
Output is correct |
3 |
Correct |
3 ms |
10584 KB |
Output is correct |
4 |
Correct |
7 ms |
10588 KB |
Output is correct |
5 |
Correct |
6 ms |
10588 KB |
Output is correct |
6 |
Correct |
5 ms |
10588 KB |
Output is correct |
7 |
Correct |
6 ms |
10588 KB |
Output is correct |
8 |
Correct |
7 ms |
10732 KB |
Output is correct |
9 |
Correct |
7 ms |
10736 KB |
Output is correct |
10 |
Correct |
8 ms |
10736 KB |
Output is correct |
11 |
Correct |
8 ms |
10588 KB |
Output is correct |
12 |
Correct |
8 ms |
10584 KB |
Output is correct |
13 |
Correct |
9 ms |
10588 KB |
Output is correct |
14 |
Correct |
18 ms |
10724 KB |
Output is correct |
15 |
Correct |
10 ms |
10740 KB |
Output is correct |
16 |
Correct |
9 ms |
10736 KB |
Output is correct |
17 |
Correct |
9 ms |
10588 KB |
Output is correct |
18 |
Correct |
11 ms |
10736 KB |
Output is correct |
19 |
Correct |
9 ms |
10592 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
10588 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
3 ms |
10588 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |