This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "debug.h"
#else
#define debug(...) 42
#endif
const int N = 1e5 + 5;
int n;
int nxt[N], a[N], b[N], c[N];
bool vis[N], in[N];
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> nxt[i] >> c[i];
}
for (int i = 1; i <= n; ++i) {
if (!vis[i]) {
int j = i;
for (; !vis[j]; j = nxt[j]) {
vis[j] = in[j] = 1;
}
for (int k = i; k != j; k = nxt[k]) {
in[k] = 0;
}
}
}
if (count(in + 1, in + n + 1, 1) == n) {
cout << 0;
exit(0);
}
for (int i = 1; i <= n; ++i) {
a[nxt[i]] = max(a[nxt[i]], c[i]);
if (!in[i]) {
b[nxt[i]] = max(b[nxt[i]], c[i]);
}
}
long long res = 0;
for (int i = 1; i <= n; ++i) {
res += c[i] - a[i];
}
for (int i = 1; i <= n; ++i) {
if (in[i]) {
int ma = -1e9;
for (int j = i; in[j]; j = nxt[j]) {
in[j] = 0;
ma = max(ma, b[j] - a[j]);
}
res -= ma;
}
}
cout << res;
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... |