Skip to content

Commit 90ecac8

Browse files
committed
[Gold V] Title: 숫자고르기, Time: 104 ms, Memory: 14132 KB -BaekjoonHub
1 parent 03b1234 commit 90ecac8

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# [Gold V] 숫자고르기 - 2668
2+
3+
[문제 링크](https://www.acmicpc.net/problem/2668)
4+
5+
### 성능 요약
6+
7+
메모리: 14132 KB, 시간: 104 ms
8+
9+
### 분류
10+
11+
깊이 우선 탐색, 그래프 이론, 그래프 탐색
12+
13+
### 제출 일자
14+
15+
2025년 4월 19일 16:30:08
16+
17+
### 문제 설명
18+
19+
<p>세로 두 줄, 가로로 N개의 칸으로 이루어진 표가 있다. 첫째 줄의 각 칸에는 정수 1, 2, …, N이 차례대로 들어 있고 둘째 줄의 각 칸에는 1이상 N이하인 정수가 들어 있다. 첫째 줄에서 숫자를 적절히 뽑으면, 그 뽑힌 정수들이 이루는 집합과, 뽑힌 정수들의 바로 밑의 둘째 줄에 들어있는 정수들이 이루는 집합이 일치한다. 이러한 조건을 만족시키도록 정수들을 뽑되, 최대로 많이 뽑는 방법을 찾는 프로그램을 작성하시오. 예를 들어, N=7인 경우 아래와 같이 표가 주어졌다고 하자.</p>
20+
21+
<p><img alt="" src="https://www.acmicpc.net/upload/images/u5JZnfExdtFXjmR.png" style="width: 262px; height: 61px; "></p>
22+
23+
<p>이 경우에는 첫째 줄에서 1, 3, 5를 뽑는 것이 답이다. 첫째 줄의 1, 3, 5밑에는 각각 3, 1, 5가 있으며 두 집합은 일치한다. 이때 집합의 크기는 3이다. 만약 첫째 줄에서 1과 3을 뽑으면, 이들 바로 밑에는 정수 3과 1이 있으므로 두 집합이 일치한다. 그러나, 이 경우에 뽑힌 정수의 개수는 최대가 아니므로 답이 될 수 없다.</p>
24+
25+
### 입력
26+
27+
<p>첫째 줄에는 N(1≤N≤100)을 나타내는 정수 하나가 주어진다. 그 다음 줄부터는 표의 둘째 줄에 들어가는 정수들이 순서대로 한 줄에 하나씩 입력된다.</p>
28+
29+
### 출력
30+
31+
<p>첫째 줄에 뽑힌 정수들의 개수를 출력하고, 그 다음 줄부터는 뽑힌 정수들을 작은 수부터 큰 수의 순서로 한 줄에 하나씩 출력한다.</p>
32+
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
static boolean[] visited;
7+
static boolean[] finished;
8+
static List<Integer> list;
9+
static int[] num;
10+
11+
public static void main(String[] args) throws IOException {
12+
13+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
14+
15+
int N = Integer.parseInt(br.readLine());
16+
17+
num = new int[N + 1];
18+
visited = new boolean[N + 1];
19+
finished = new boolean[N + 1];
20+
list = new ArrayList<>();
21+
22+
for (int i = 1; i <= N; i++) {
23+
num[i] = Integer.parseInt(br.readLine());
24+
}
25+
26+
for (int i = 1; i <= N; i++) {
27+
if (!visited[i]) {
28+
dfs(i);
29+
}
30+
}
31+
32+
Collections.sort(list);
33+
System.out.println(list.size());
34+
for (int n : list) {
35+
System.out.println(n);
36+
}
37+
}
38+
39+
static void dfs(int cur) {
40+
visited[cur] = true;
41+
int next = num[cur];
42+
43+
if (!visited[next]) {
44+
dfs(next);
45+
} else if (!finished[next]) {
46+
for (int i = next; i != cur; i = num[i]) {
47+
list.add(i);
48+
}
49+
list.add(cur);
50+
}
51+
52+
finished[cur] = true;
53+
}
54+
}

0 commit comments

Comments
 (0)