Typical topological sorting problem .. why is it 'difficult'?
#include <iostream> #include <string> #include <vector> #include <queue> using namespace std; #define MAX_CNT 1000001 vector<long> outdeg(MAX_CNT); vector<long> inc[MAX_CNT]; void add_edge(long a, long b) { outdeg[a]++; inc[b].push_back(a); } int main() { // Get input and compose graph vector<long> ar(MAX_CNT), used(MAX_CNT); long n; cin >> n; for (int i = 1; i <= n; i++) { long q; cin >> q; for (int j = 1; j <= q; j++) { cin >> ar[j]; used[ar[j]] = 1; } // setup edgedegree info for (int j = 2; j <= q; j++) { add_edge(ar[j], ar[j - 1]); } } // maintain a min-heap of all leaves priority_queue<long, vector<long>,greater<long>> leaves; for (int i = 1; i <= MAX_CNT; i++) { if (outdeg[i] == 0 && used[i] == 1) leaves.push(i); } // iteratively, we poppush old ew leaves vector<long> ans; while (leaves.size()) { long v = leaves.top(); leaves.pop(); ans.push_back(v); for (int i = 0; i<inc[v].size(); i++) { long id = inc[v][i]; outdeg[id]--; if (!outdeg[id]) leaves.push(id); } } for (int i = 0; i<ans.size(); i++) { if (i)cout << " "; cout << ans[i]; } cout << endl; return 0; }