This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//In the name of God
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const ll maxn = 512;
const ll mod = 1e9 + 7;
const ll inf = 1e15;
#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define file_io freopen("input.txt", "r+", stdin);freopen("output.txt", "w+", stdout);
#define pb push_back
#define Mp make_pair
#define F first
#define S second
#define Sz(x) ll((x).size())
#define all(x) (x).begin(), (x).end()
ll pw(ll a, ll b){
ll c = 1;
while(b){
if(b & 1) c = c * a % mod;
a = a * a % mod;
b >>= 1;
}
return c;
}
int n, m, p[maxn], c[maxn];
vector<int> g[maxn];
ll dp[maxn][maxn];
void dfs(int v){
for(int u : g[v]){
dfs(u);
for(int i = c[v]; i < maxn; i++){
dp[v][i] += dp[u][i - c[v]];
}
}
if(g[v].empty()){
fill(dp[v], dp[v] + maxn, inf);
dp[v][c[v]] = 0;
}
for(int i = 0; i < c[v]; i++){
dp[v][i] = inf;
}
ll mn = inf;
for(int i = 0; i < maxn; i++){
dp[v][i] = min(dp[v][i], i + mn);
mn = min(mn, dp[v][i] - i);
}
mn = inf;
for(int i = maxn; i--;){
dp[v][i] = min(dp[v][i], mn - i);
mn = min(mn, dp[v][i] + i);
}
return;
}
void solve(){
ll ans = inf;
for(int i = 2; i <= n + m; i++){
ll x = 0;
for(int j = 2; j <= n + m; j++){
x += abs(c[i] - c[j]);
}
ans = min(ans, x);
}
cout << ans << "\n";
return;
}
int main(){
fast_io;
cin >> n >> m;
for(int i = 2; i <= n + m; i++){
cin >> p[i] >> c[i];
g[p[i]].pb(i);
}
if(n == 1){
solve();
return 0;
}
dfs(1);
ll ans = inf;
for(int i = 0; i < maxn; i++){
ans = min(ans, dp[1][i]);
}
cout << ans << "\n";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |