n명의 학생이 있고 i번 학생은 지목당했을 때 a[i]를 대타로 지정한다. 이 때 모든 i에 대해서 두번 지목되는 학생을 구하는 문제다.


dfs돌면서 방문했던 곳이면 그곳이 정답이다. 이걸 1<=i<=n까지 memset을 계속 하면서 구하면 된다.


#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <string>
#include <math.h>
#include <string.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;

int n, t;
int p[1001], c[1001];
vector<int> ans;

void dfs(int x) {
	if (c[x] == 2) {
		ans.push_back(x);
		return;
	}
	c[x]++;
	dfs(p[x]);
}

int main() {
	ios::sync_with_stdio(false); cin.tie(0);
	cin >> n;
	for (int i = 1; i <= n; ++i)
		cin >> p[i];

	for (t = 1; t <= n; ++t) {
		memset(c, 0, sizeof(c));
		dfs(t);
	}
	for (auto i : ans)
		cout << i << " ";
	return 0;
}


'codeforces > #503 div2' 카테고리의 다른 글

A. New Building for SIS  (0) 2018.08.15

+ Recent posts