https://bcp0109.tistory.com/32
백준 9466번. 텀 프로젝트 (Java)
문제 링크 : https://www.acmicpc.net/problem/9466 싸이클을 형성하지 못하는 노드 갯수를 찾는 문제입니다. 일반적인 DFS로 모든 노드를 탐색하면 시간 초과가 납니다. 테스트케이스가 2 3 4 5 1 이렇게 주
bcp0109.tistory.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static boolean[] visit;
static boolean[] search;
static boolean[] solo;
static int cnt = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
while(T --> 0) {
cnt = 0;
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int[] arr = new int[N+1];
visit = new boolean[N+1];
search = new boolean[N+1];
solo = new boolean[N+1];
for(int i = 1; i <= N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
if(i == arr[i]) {
solo[i] = true;
cnt++; //혼자 소속된 팀
}
}
for(int i = 1; i <= N; i++) {
if(!search[i]) {
dfs(i,arr);
}
}
sb.append(N-cnt).append('\n');
}
System.out.println(sb);
}
static void dfs(int depth, int[] arr) {
if(search[depth] == true) { //사이클에 포함되지 않은 학생이 사이클에 포함된 학생을 선택했을때
return;
}
int choice = arr[depth];
visit[depth] = true;
search[depth] = true;
if(!visit[choice]) { //방문하지 않았다면
dfs(choice, arr);
}
else if(!solo[choice]){ //방문했다면(사이클을 형성한다) 혼자 소속된 팀은 제외
cnt++; //사이클의 마지막 476에서 6을 먼저 추가
for(int i = choice; i != depth; i = arr[i]) { //다음 depth 부터 현재 depth까지 arr을 돌면서 소속 된 것을 찾는다 476에서 4와 7을 추가 6이 되면 멈춤
cnt++;
}
}
visit[depth] = false;
}
}
'백준' 카테고리의 다른 글
[백준] 1912 연속합 [자바] (0) | 2021.12.21 |
---|---|
[백준] 2636 치즈 [자바] (0) | 2021.12.11 |
[백준] 2206 벽 부수고 이동하기 [자바] (0) | 2021.12.07 |
[백준] 7576 토마토 [자바] (0) | 2021.12.07 |
[백준] 2579 계단 오르기 [자바] (0) | 2021.12.03 |