순열 사이클

BiBi·2021년 2월 7일
0

코딩테스트연습

목록 보기
60/66
#include <iostream>
#include <queue>
#include <stdio.h>

int arr[1001];
bool visited[1001];
int t, n;
int cnt;

void bfs(int v) {
	if (v == arr[v]) {
		visited[v] = true;
		cnt++;
		return;
	}
	if (visited[v] == true) {
		cnt++;
		return;
	}
	visited[v] = true;
	bfs(arr[v]);
	
}



int main() {
	scanf("%d", &t);
	for (int i = 0;i < t;i++) {
		for (int j = 1;j <= n;j++) {
			arr[j] = 0;
			visited[j] = 0;
			cnt = 0;
		}
		scanf("%d", &n);
		for (int j = 1;j <= n;j++) {
			int a;
			scanf("%d", &a);
			arr[j] = a;
		}
		for (int j = 1;j <= n;j++) {
			if (!visited[j]) {
				bfs(j);
			}
		}
		printf("%d\n", cnt);
	}
}
profile
Server Network Engineer

0개의 댓글