Submission #1070177

#TimeUsernameProblemLanguageResultExecution timeMemory
1070177juicyTelegraph (JOI16_telegraph)C++17
100 / 100
31 ms3748 KiB
#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, cnt = 0;
            for (; !vis[j]; j = nxt[j]) {
                ++cnt;
                vis[j] = in[j] = 1;
            }
            for (int k = i; k != j; k = nxt[k]) {
                --cnt;
                in[k] = 0;
            }
            if (cnt == 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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...