[백준] 10451번 : 순열 사이클

2021. 1. 20. 17:06Algorithm/백준

 

10451번: 순열 사이클

1부터 N까지 정수 N개로 이루어진 순열을 나타내는 방법은 여러 가지가 있다. 예를 들어, 8개의 수로 이루어진 순열 (3, 2, 7, 8, 1, 4, 5, 6)을 배열을 이용해 표현하면 \(\begin{pmatrix} 1 & 2 &3&4&5&6&7&8 \\  3

www.acmicpc.net

 

#include <iostream>
#include<vector>
#include<string>
#include<queue>
#define MAX 1001
using namespace std;

int g[MAX];
int visit[MAX];
int cycle = 0;

void dfs(int x) {
	if (visit[x] == true) {
		cycle++;
		return;
	}
	visit[x] = true;
	dfs(g[x]);
}

int main() {

	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int t,T, n;

	cin >> T;
	while (T--) {
		cin >> t;
		cycle = 0;

		for (int i = 1;i <= t;i++) {
			g[i] = 0;
			visit[i] = 0;
		}

		for (int i = 0;i < t;i++) {
			cin >> n;
			g[i + 1]=n;
		}

		for (int i = 1;i <= t;i++) {
			if (visit[i] == true) continue;
			dfs(i);
		}
		cout << cycle << '\n';
	}
	return 0;
}

'Algorithm > 백준' 카테고리의 다른 글

[백준] 11656번: 접미사 배열  (0) 2021.01.20
[백준] 2331번: 반복수열  (0) 2021.01.20
[백준] 1707번: 이분 그래프  (0) 2021.01.20
[백준] 11724번: 연결 요소의 개수  (0) 2021.01.20
[백준] 10824번 :네 수  (0) 2021.01.19