이것저것
c++ topological sort
문자메일
2017. 10. 5. 18:04
#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>
#define MAX_N 32000
using namespace std;
vector<vector<int>> vt;
stack<int> st;
int n, m, x, y, visited[ MAX_N + 1];
void dfs(int v)
{
visited[v] = true;
for (auto i : vt[v]) //auto는 변수형을 초기화의 값으로 자동으로 지정해주는 역할
{
if (visited[i])
continue;
dfs(i);
}
st.push(v);
}
int main(void){
scanf("%d %d", &n, &m);
vt.resize(n + 1);
for (int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
vt[x].push_back(y); //vector의맨 끝에 요소를 삽입
}
for (int i = 1; i <= n; i++){
if (!visited[i])
dfs(i);
}
while (st.size()){
printf("%d ", st.top());
st.pop();
}
return 0;
}
//auto a = 55; //int 형
//auto b = 11.5; // float형
//auto c = 'c'; //char형