Editorial for Work Stealing


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.
#include <bits/stdc++.h>

using namespace std;

bool visited[1000];
vector<int> adjList[1000], result;

void dfs(int v) {
    visited[v] = true;
    for (int u : adjList[v])
        if (!visited[u])
            dfs(u);
    result.push_back(v);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    bool occurs[1000];
    memset(occurs, false, 1000 * sizeof(bool));
    memset(visited, false, 1000 * sizeof(bool));

    for (int i = 0; i < n; i++)
    {
        int after, before;
        cin >> after >> before;
        after--, before--;

        adjList[before].emplace_back(after);
        occurs[before] = true;
        occurs[after] = true;
    }

    for (int i = 0; i < 1000; i++)
        if (occurs[i] && !visited[i])
            dfs(i);

    cout << result.size() << '\n';
    /*
     * for (int i = result.size() - 1; i >= 0; i--)
     *     cout << result[i] + 1 << ' ';
     * cout.close();
     */

    for (auto & i : adjList)
        i.clear();
    result.clear();
    return 0;
}