#include <bits/stdc++.h>
using namespace std;
const int N = 5001;
const long long inf = (long long) 4e18L;
int n, m;
vector<pair<int, long long>> g[N];
long long dp[N][302];
long long sol(int u, int left) {
if (g[u].size() == 0) {
assert(left == 0);
return 0;
}
long long& ret = dp[u][left];
if (ret != -1) {
return ret;
}
ret = 0;
for (pair<int, long long> _p : g[u]) {
long long sub = inf;
int v = _p.first;
long long w = _p.second;
if (g[v].size() == 0) {
sub = abs(w - left);
ret += sub;
continue;
}
for (int j = 0; j <= left; j++) {
sub = min(sub, abs(w - j) + sol(v, left - j));
}
ret += sub;
}
return ret;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
if (n == 1) {
vector<long long> cs;
for (int i = 1; i < n + m; i++) {
int p;
long long c;
cin >> p >> c;
cs.emplace_back(c);
}
sort(cs.begin(), cs.end());
long long loc = cs[cs.size() / 2];
long long ans = 0;
for (int i = 0; i < n; i++) {
ans += abs(loc - cs[i]);
}
cout << ans << '\n';
return 0;
}
long long res = 0;
for (int i = 1; i < n + m; i++) {
int p;
long long c;
cin >> p >> c;
g[p - 1].emplace_back(i, c);
res += c;
}
memset(dp, -1, sizeof dp);
for (int i = 0; i < 301; i++) {
res = min(res, sol(0, i));
}
cout << res << '\n';
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
332 KB |
Output is correct |
2 |
Incorrect |
1 ms |
332 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
8 ms |
12236 KB |
Output is correct |
2 |
Correct |
10 ms |
12236 KB |
Output is correct |
3 |
Correct |
13 ms |
12236 KB |
Output is correct |
4 |
Correct |
36 ms |
12236 KB |
Output is correct |
5 |
Correct |
26 ms |
12256 KB |
Output is correct |
6 |
Correct |
27 ms |
12252 KB |
Output is correct |
7 |
Correct |
28 ms |
12236 KB |
Output is correct |
8 |
Correct |
33 ms |
12256 KB |
Output is correct |
9 |
Correct |
40 ms |
12236 KB |
Output is correct |
10 |
Correct |
41 ms |
12236 KB |
Output is correct |
11 |
Correct |
49 ms |
12232 KB |
Output is correct |
12 |
Correct |
52 ms |
12236 KB |
Output is correct |
13 |
Correct |
50 ms |
12236 KB |
Output is correct |
14 |
Correct |
103 ms |
12260 KB |
Output is correct |
15 |
Correct |
53 ms |
12236 KB |
Output is correct |
16 |
Correct |
53 ms |
12236 KB |
Output is correct |
17 |
Correct |
52 ms |
12236 KB |
Output is correct |
18 |
Correct |
53 ms |
12236 KB |
Output is correct |
19 |
Correct |
46 ms |
12236 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
332 KB |
Output is correct |
2 |
Incorrect |
1 ms |
332 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
332 KB |
Output is correct |
2 |
Incorrect |
1 ms |
332 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |