This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/*
Code written by Talant I.D.
*/
#include <bits/stdc++.h>
//~ #include <ext/pb_ds/assoc_container.hpp>
//~ using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
//~ typedef tree <int, null_type, less_equal <int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
#define precision(n) fixed << setprecision(n)
#define pb push_back
#define ub upper_bound
#define lb lower_bound
#define mp make_pair
#define eps (double)1e-9
#define PI 2*acos(0.0)
#define endl "\n"
#define sz(v) int((v).size())
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define do_not_disturb ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define OK cout << "OK" << endl;
const int mod = 1e9+7;
ll mode(ll a) {
while (a < 0) {
a += mod;
}
return a % mod;
}
ll subt(ll a, ll b) {
return mode(mode(a)-mode(b));
}
ll add(ll a, ll b) {
return mode(mode(a)+mode(b));
}
ll mult(ll a, ll b) {
return mode(mode(a)*mode(b));
}
ll binpow(ll a, ll b) {
ll res = 1;
while (b) {
if (b&1) res = mult(res, a);
a = mult(a, a);
b >>= 1;
}
return res;
}
const int N = 303;
ll dp[N][N];
vector <pii> graph[N];
void dfs(int v, int p) {
int children = 0;
for (auto to : graph[v]) {
if (to.first == p) {
continue;
}
children++;
dfs(to.first, v);
}
if (!children) {
dp[v][0] = 0;
}
else {
for (int i = 0; i <= 300; i++) {
ll res = 0;
for (auto to : graph[v]) {
if (to.first == p) continue;
ll mn = 1e12;
for (int j = 0; j <= i; j++) {
mn = min(mn, dp[to.first][j]+abs(j+to.second-i));
}
res += mn;
}
dp[v][i] = min(dp[v][i], res);
}
}
}
int main() {
do_not_disturb
int n, m;
cin >> n >> m;
for (int i = 2; i <= n+m; i++) {
int p, w;
cin >> p >> w;
graph[p].pb(mp(i, w));
graph[i].pb(mp(p, w));
}
if (n == 1) {
ll ans = 9e18;
for (auto to : graph[1]) {
ll sum = 0;
for (auto to2 : graph[1]) {
sum += abs(to.second-to2.second);
}
ans = min(ans, sum);
}
cout << ans << endl;
}
else if (n+m <= 300) {
for (int i = 0; i <= 300; i++) {
for (int j = 0; j <= 300; j++) {
dp[i][j] = 1e12;
}
}
dfs(1, 1);
ll ans = 9e18;
for (int i = 0; i <= 300; i++) {
ans = min(ans, dp[1][i]);
}
cout << ans << endl;
}
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... |