Submission #333487

# Submission time Handle Problem Language Result Execution time Memory
333487 2020-12-06T13:03:11 Z ncduy0303 Forensic (NOI12_forensic) C++17
25 / 25
3 ms 1132 KB
#include <bits/stdc++.h>

using namespace std;

#define ar array
#define ll long long

const int MAX_N = 1e5 + 1;
const int MOD = 1e9 + 7;
const int INF = 1e9;
const ll LINF = 1e18;

int n, nxt[MAX_N], vis[MAX_N], dp[MAX_N], st_chain, mx_chain;
bool cycle;

void dfs1(int u) {
    if (u == -1) return;
    if (vis[u]) {
        cycle = true;
        return;
    }
    vis[u] = 1;
    dp[u] = 0;
    st_chain++;
    dfs1(nxt[u]);
}

int dfs2(int u) {
    if (u == -1) return 0;
    if (u == 0 || (vis[u] == 1 && cycle)) return -INF;
    if (dp[u] != -1) return dp[u];
    if (vis[u] == 2) return -INF;
    vis[u] = 2;
    return dp[u] = dfs2(nxt[u]) + 1;
}

void solve() {
    cin >> n;
    for (int i = 0; i < n; i++) cin >> nxt[i];
    if (nxt[0] == 0) {
        cout << 1 << "\n";
        return;
    }
    memset(dp, -1, sizeof dp);
    dfs1(0);
    for (int i = 0; i < n; i++) {
        if (!vis[i]) {
            mx_chain = max(mx_chain, dfs2(i));
        }
    }
    cout << st_chain + mx_chain << "\n";
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);

    int tc = 1;
    // cin >> tc;
    for (int t = 1; t <= tc; t++) {
        // cout << "Case #" << t  << ": ";
        solve();
    }
}
# Verdict Execution time Memory Grader output
1 Correct 1 ms 748 KB Output is correct
2 Correct 1 ms 748 KB Output is correct
3 Correct 1 ms 748 KB Output is correct
4 Correct 1 ms 768 KB Output is correct
5 Correct 1 ms 748 KB Output is correct
# Verdict Execution time Memory Grader output
1 Correct 1 ms 768 KB Output is correct
2 Correct 1 ms 748 KB Output is correct
3 Correct 1 ms 748 KB Output is correct
4 Correct 1 ms 748 KB Output is correct
5 Correct 1 ms 748 KB Output is correct
# Verdict Execution time Memory Grader output
1 Correct 1 ms 748 KB Output is correct
2 Correct 1 ms 748 KB Output is correct
3 Correct 1 ms 748 KB Output is correct
4 Correct 1 ms 748 KB Output is correct
5 Correct 1 ms 748 KB Output is correct
# Verdict Execution time Memory Grader output
1 Correct 2 ms 492 KB Output is correct
2 Correct 3 ms 1132 KB Output is correct
3 Correct 2 ms 1004 KB Output is correct
4 Correct 3 ms 1024 KB Output is correct
5 Correct 2 ms 876 KB Output is correct