Skip to content

Instantly share code, notes, and snippets.

@KT-Yeh
Created March 7, 2014 08:31
Show Gist options
  • Save KT-Yeh/9407640 to your computer and use it in GitHub Desktop.
Save KT-Yeh/9407640 to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <vector>
using namespace std;
void DFS(int n, int visit[], vector<int> toNode[], vector<int> &ans);
int main()
{
int N, M, a, b;
while (scanf("%d %d", &N, &M) && (N || M)) {
vector<int> toNode[101];
vector<int> ans;
bool connect[101] = {0};
int visit[101] = {0};
while (M--) {
scanf("%d %d", &a, &b);
toNode[a].push_back(b);
connect[b] = 1;
}
for (int i = 1; i <= N; ++i) {
if (!connect[i])
DFS(i ,visit, toNode, ans);
}
for (auto iter = ans.end() - 1; iter != ans.begin(); --iter)
printf("%d ", *iter);
printf("%d\n", *ans.begin());
}
}
void DFS(int n, int visit[],vector<int> toNode[], vector<int> &ans)
{
if (visit[n] == 1) return;
visit[n] = 1;
for (int nxt : toNode[n]) {
if (visit[nxt] != 2)
DFS(nxt, visit, toNode, ans);
}
visit[n] = 2;
ans.push_back(n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment