Is to sort the output in a certain order.
For example, if a owes B money, it cannot output a first and then B.
The trick in this question is that a cannot be output first and then B, but B can be output first and then.
Therefore, you can create a graph based on the relationship between A and B, and then search for the DFS depth first, and then record the reverse point to output the reverse point, that is, the money a owes B, first output B and then output A. Then the order meets the requirements.
It's a tricky question. Be careful. Otherwise, it will be done for half a day.
Question connection: http://codeforces.com/problemset/problem/412/D
#include <stdio.h>#include <vector>using std::vector;const int MAX_S = 30001;vector<int> gra[MAX_S];bool vis[MAX_S] = {0};vector<int> res;int N, M;void dfsReverseNodes(int u){vis[u] = true;for (int i = 0; i < (int)gra[u].size(); i++){int v = gra[u][i];if (!vis[v]) dfsReverseNodes(v);}res.push_back(u);}int main(){int u, v;scanf("%d %d", &N, &M);for (int i = 1; i <= M; i++){scanf("%d %d", &u, &v);gra[u].push_back(v);}for (int i = 1; i <= N; i++){if (!vis[i]) dfsReverseNodes(i);}for (int i = 0; i < (int)res.size(); i++){printf("%d ", res[i]);}return 0;}