๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 10451๋ฒˆ - ์ˆœ์—ด ์‚ฌ์ดํด

by ์•ˆ์ฃผํ˜• 2021. 10. 16.
 

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

 

 

//  Copyright © 2021 ์•ˆ์ฃผํ˜•. All rights reserved.
//  https://github.com/dkswnkk
//  https://www.acmicpc.net/problem/10451
//  BOJ10451 ์ˆœ์—ด ์‚ฌ์ดํด

#include <iostream>
#include <vector>
#include <memory.h>
using namespace std;

int graph[1001];
int visited[1001];
bool check;

void dfs(int start,int next){
    visited[start]=1;
    visited[next]=1;
    if(next==start){
        check= true;
        return;
    }
    else{
        dfs(start,graph[next]);
    }

}

int main(){

    int T; cin>>T;
    while(T--){
        int ans=0;
        int N; cin>>N;

        for(int i=1; i<=N; i++){
            cin>>graph[i];
        }
        for(int i=1; i<=N; i++){
            if(!visited[i])dfs(i,graph[i]);
            if(check){
                ans++;
                check=false;
            }
        }
        cout<<ans<<'\n';
        memset(visited, 0, sizeof(visited));
    }

}

๋Œ“๊ธ€