문제 출처
https://www.acmicpc.net/problem/9466
9466번: 텀 프로젝트
문제 이번 가을학기에 '문제 해결' 강의를 신청한 학생들은 텀 프로젝트를 수행해야 한다. 프로젝트 팀원 수에는 제한이 없다. 심지어 모든 학생들이 동일한 팀의 팀원인 경우와 같이 한 팀만 있을 수도 있다. 프로젝트 팀을 구성하기 위해, 모든 학생들은 프로젝트를 함께하고 싶은 학생을 선택해야 한다. (단, 단 한 명만 선택할 수 있다.) 혼자 하고 싶어하는 학생은 자기 자신을 선택하는 것도 가능하다. 학생들이(s1, s2, ..., sr)이라 할 때, r=
www.acmicpc.net
접근 방식 및 풀이
- DFS를 이용하여 시작점과 만나면는 사이클 그래프의 노드 개수를 전체 학생수에서 뺀다.
- 참고
https://pangsblog.tistory.com/35
[백준-9466]-[DFS]-텀 프로젝트(JAVA)
문제링크 : https://www.acmicpc.net/problem/9466 이 문제는 백준_2668번 문제 와 비슷한 문제지만 절대 비슷하게 풀면 큰일 난다. 본인의 2668 번 문제대로 풀었더니 시간 초과가 발생했다. 이전글 보기 --> 201..
pangsblog.tistory.com
소스 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static int size, count;
static int[] students;
static int[] check;
static int[] cycle;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = sc.nextInt();
for (int i = 0; i <total ; i++) {
int size = sc.nextInt();
students = new int[size+1];
check = new int[size+1];
cycle = new int[size+1];
for (int j = 1; j <= size ; j++) {
students[j] = sc.nextInt();
}
count =0;
for (int p = 1; p <=size ; p++) {
if(check[p] != 0){
continue;
}
if(check[students[p]] == 0){
count += dfs(p,p,1);
}
}
int result = size - count;
System.out.println(result);
}
}
private static int dfs(int start, int num, int level ){
check[num] = level;
cycle[num] = start;
int next = students[num];
if(check[next] != 0 && start == cycle[next]){
return level-check[next]+1;
} else if(check[next] != 0 && start != cycle[next]) {
return 0;
}
return dfs(start, next, level+1);
}
}
결과
'Competition > Baekjoon' 카테고리의 다른 글
[백준] 11724번 연결요소 구하기 (0) | 2020.03.29 |
---|---|
[백준] 1931번 자바 회의실배정 (0) | 2020.03.27 |
[백준] 2178번 미로 (0) | 2020.03.27 |