-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15684.java
More file actions
97 lines (87 loc) · 2.71 KB
/
Copy path15684.java
File metadata and controls
97 lines (87 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// https://www.acmicpc.net/problem/15684
// 사다리 조작
import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
static int n, m, h;
static int[][] links;
static List<Integer> xnodes, ynodes;
static int min, start[];
static final int MIN_ANSWER = 3;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(reader.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
links = new int[h][n-1];
for(int i=0; i<m; i++){
st = new StringTokenizer(reader.readLine());
int level = Integer.parseInt(st.nextToken())-1;
int point = Integer.parseInt(st.nextToken())-1;
links[level][point] = 1;
}
// when answer is 0
start = new int[n];
if(allPass()){
System.out.println(0);
return;
}
// get search nodes
xnodes = new ArrayList<>();
ynodes = new ArrayList<>();
for(int i=0; i<h; i++){
for(int j=0; j<n-1; j++){
if(isLinkable(i, j)){
xnodes.add(i);
ynodes.add(j);
}
}
}
min = -1;
dfs(0, 0);
System.out.println(min);
}
public static void dfs(int idx, int count){
if(min == -1 && count >= MIN_ANSWER) return;
if(min != -1 && count >= min) return;
if(idx == xnodes.size()) return;
int x = xnodes.get(idx), y = ynodes.get(idx);
if(isLinkable(x, y)){
links[x][y] = 1;
if(allPass()){
min = count+1;
links[x][y] = 0;
return;
}
else{
dfs(idx+1, count+1);
links[x][y] = 0;
}
}
dfs(idx+1, count);
}
public static boolean allPass(){
int tmp;
for(int i=0; i<n; i++) start[i] = i;
for(int i=0; i<h; i++){
for(int j=0; j<n-1; j++){
if(links[i][j] == 1){
tmp = start[j];
start[j] = start[j+1];
start[j+1] = tmp;
}
}
}
for(int i=0; i<n; i++)
if(start[i] != i) return false;
return true;
}
public static boolean isLinkable(int i, int j){
if(links[i][j] == 1) return false;
if(j-1 >= 0 && links[i][j-1] == 1) return false;
if(j+1 < n-1 && links[i][j+1] == 1) return false;
return true;
}
}