Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : G1. Medium Demon Problem (easy version)

#include <bits/stdc++.h>
using namespace std;

class Graph {
  public:
    int n;
    vector<vector<int>> adj;
    Graph(int n) {
        this->n = n;
        adj.resize(n);
    }

    int remove_indegree_zero();
};

int Graph::remove_indegree_zero() {
    vector<int> indegree(n);
    for (int v = 0; v < n; v++) {
        for (auto child : adj[v]) {
            indegree[child]++;
        }
    }
    queue<int> q;
    for (int v = 0; v < n; v++) {
        if (indegree[v] == 0) {
            q.push(v);
        }
    }

    int year = 1;
    while (!q.empty()) {
        year++;

        // Trick to traverse all nodes in a level at once.
        int sz = q.size();
        while (sz--) {
            int v = q.front();
            q.pop();
            for (auto child : adj[v]) {
                indegree[child]--;
                if (indegree[child] == 0) {
                    q.push(child);
                }
            }
        }
    }
    return year + 1;
}

void solve() {
    int n;
    cin >> n;
    Graph g(n);

    for (int i = 0; i < n; i++) {
        int c;
        cin >> c;
        c--;
        g.adj[i].push_back(c);
    }
    cout << g.remove_indegree_zero() << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        solve();
    }
}