Skip to content

Commit cf7ce99

Browse files
beberichetony9402
andauthored
[ADD] baekjoon 12931 java solution (#79)
* [ADD] baekjoon 12931 java solution * Refactoring --------- Co-authored-by: Minsang Kim <[email protected]>
1 parent f962c56 commit cf7ce99

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

solutions/baekjoon/12931/Main.java

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Authored by: beberiche
2+
// Co-authored by: -
3+
// Link: http://boj.kr/6c68b4d99ce3457a948740d3a30d4799
4+
5+
import java.util.*;
6+
import java.io.*;
7+
8+
public class Main {
9+
public static void main(String[] args) {
10+
FastReader rd = new FastReader();
11+
int N = rd.nextInt();
12+
int a1[] = new int[N];
13+
int a2[] = new int[N];
14+
15+
// 0
16+
for (int i = 0; i < a1.length; i++) {
17+
a1[i] = rd.nextInt();
18+
}
19+
20+
21+
// a1 -> a2 만들기
22+
int ret = 0;
23+
while (!check(a1, a2)) {
24+
// 홀수가 있는지 확인
25+
boolean check = false;
26+
for (int i = 0; i < N; i++) {
27+
if (a1[i] % 2 == 1) {
28+
check = true;
29+
a1[i]--;
30+
ret++;
31+
}
32+
}
33+
34+
// 다 짝수라면?
35+
if (!check) {
36+
for (int i = 0; i < N; i++) {
37+
a1[i] /= 2;
38+
}
39+
ret++;
40+
}
41+
}
42+
System.out.println(ret);
43+
}
44+
45+
private static boolean check(int[] a1, int[] a2) {
46+
for (int i = 0; i < a1.length; i++) {
47+
if (a1[i] != a2[i]) return false;
48+
}
49+
return true;
50+
}
51+
52+
static class FastReader {
53+
BufferedReader br;
54+
StringTokenizer st;
55+
56+
public FastReader() {
57+
br = new BufferedReader(new InputStreamReader(System.in));
58+
}
59+
60+
String next() {
61+
while (st == null || !st.hasMoreElements()) {
62+
try {
63+
st = new StringTokenizer(br.readLine());
64+
} catch (IOException e) {
65+
e.printStackTrace();
66+
}
67+
}
68+
return st.nextToken();
69+
}
70+
71+
int nextInt() {
72+
return Integer.parseInt(next());
73+
}
74+
75+
long nextLong() {
76+
return Long.parseLong(next());
77+
}
78+
79+
double nextDouble() {
80+
return Double.parseDouble(next());
81+
}
82+
83+
String nextLine() {
84+
String str = "";
85+
try {
86+
str = br.readLine();
87+
} catch (IOException e) {
88+
e.printStackTrace();
89+
}
90+
return str;
91+
}
92+
}
93+
}
94+
95+
/* Solution Description
96+
97+
1. 고민이 필요한 문제. `A → B` 로 변화시키는 것이 아닌 `B → A` 로 바꾼다는 생각의 전환이 필요하다.
98+
99+
2. **베열에 있는 모든 값을 두 배 시킨다** 는 연산은 결국 배열의 모든 값이 **짝수**가 됨을 의미한다.
100+
따라서 B → A로 전향할 때는, 홀수가 있는지 확인하고 홀수가 있다면 `-1` 차감하여 짝수로 만들어주고,
101+
`B` 의 모든 값이 짝수인 경우에만 `2` 로 나눠주는 것으로 최소 횟수로 `B` 를 `A` 로 만드는 것이 가능하다.
102+
103+
*/

0 commit comments

Comments
 (0)