https://www.acmicpc.net/problem/10451
문제 1부터 N까지 정수 N개로 이루어진 순열을 나타내는 방법은 여러가지가 있다. 예를 들어, 8개의 수로 이루어진 순열 (3, 2, 7, 8, 1, 4, 5, 6)을 배열을 이용해 표현하면 와 같다. 또는, Figure 1과 같이 방향 그래프로 나타낼 수도 있다. 순열을 배열을 이용해 로 나타냈다면, i에서 πi로 간선을 이어 그래프로 만들 수 있다. Figure 1에 나와있는 것 처럼, 순열 그래프 (3, 2, 7, 8, 1, 4, 5, 6) 에는 총 3개의 사이클이 있다. 이러한 사이클을 "순열 사이클" 이라고 한다. N개의 정수로 이루어진 순열이 주어졌을 때, 순열 사이클의 개수를 구하는 프로그램을 작성하시오. |
code>>
#include <queue>
#include <stdio.h>
#include <string.h>
int input[1001];
bool visit[1001];
int main()
{
int t, size, count, n;
scanf("%d", &t);
while (t-- > 0)
{
scanf("%d", &size);
for (int i = 1; i <= size; i++)
scanf("%d", &input[i]);
std::queue<int> q;
count = 0;
memset(visit, false, sizeof(visit));
for (int i = 1; i <= size; i++)
{
q.push(input[i]);
visit[i] = true;
n = 0;
while (!q.empty())
{
n = q.front();
q.pop();
if (!visit[n])
{
visit[n] = true;
q.push(input[n]);
}
}
if (n == i)
count++;
}
printf("%d\n", count);
}
return 0;
}
'알고리즘 > 백준' 카테고리의 다른 글
1753>최단경로 (0) | 2018.05.19 |
---|---|
1890>점프 (0) | 2018.05.13 |
1325>효율적인 해킹 (0) | 2018.05.09 |
2309>일곱난쟁이 (0) | 2018.05.01 |
1038>감소하는 수 (0) | 2018.04.30 |