10451 : 순열 사이클

풀이

.

코드

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;

int t, n;
vector<int> a[1001];
int ans, chk[1001];

void dfs(int now) {
    chk[now] = 1;
    for (int i = 0; i < a[now].size(); i++)
        if (chk[a[now][i]] != 1) dfs(a[now][i]);
}

int main() {
    cin >> t;

    while (t--) {
        cin >> n;

        for (int i = 1; i <= n; i++) {
            int v;
            cin >> v;
            a[i].push_back(v);
        }

        for (int i = 1; i <= n; i++) if (chk[i] != 1) dfs(i), ans++;
        
        cout << ans << "\n";
        
        for (int i = 1; i <= n; i++) fill(a[i].begin(), a[i].end(), 0);
        memset(chk, 0, sizeof(chk));
        ans = 0;
    }
    return 0;
}

아무말

백준, 백준 온라인 저지, BOJ, Baekjoon Online Judge, C, C++, 씨, 씨쁠쁠, JAVA, algorithm, 자바, 알고리즘, 자료구조, 문제, 문제 풀이, 풀이

wookje.kwon's profile image

wookje.kwon

2018-06-24 22:15

Read more posts by this author