문제풀이
- 전형적인 dfs탐색 문제이다.
- 컴퓨터를 1번부터 dfs탐색시켜서 탐색수가 최대인 노드들을 답으로 쓰면된다.
- 탐색을 할때마다 reset()으로 방문한 노드를 체크한 visited배열을 초기화 시켜줬다.
코드
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
#define endl "\n"
#define MAX 100000
int n, m;
vector<int> graph[MAX];
bool visited[MAX];
int cnt;
int nowMax;
vector<int> ans;
void reset() {
for (int i = 1; i <= n; i++)
{
visited[i] = false;
}
}
void dfs(int v) {
visited[v] = true;
cnt++;
for (auto w : graph[v]) {
if (!visited[w])
{
dfs(w);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
//ifstream cin; cin.open("input.txt");
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
graph[y].push_back(x);
}
for (int i = 1; i <= n; i++)
{
cnt = 0;
reset();
dfs(i);
if (cnt > nowMax)
{
ans.clear();
ans.push_back(i);
nowMax = cnt;
}
else if (cnt == nowMax) {
ans.push_back(i);
}
else {
// empty
}
}
for (auto num : ans) {
cout << num << " ";
}
}