BOJ(Java)

자바(백준) 1484 다이어트

자바생 2021. 12. 17. 11:59
728x90

오답 노트 & 새로 알게 된 점

 

문제의 식을 써보면

 

G + 기억몸무게^2 = 현재몸무게^2 으로 나타낼 수 있다.

따라서

G = (현재몸무게^2) - (기억몸무게^2)

   = (현재몸무게+기억몸무게) * (현재몸무게 - 기억몸무게)

 

getMul

투포인터를 이용하여 곱이 G가 되는 두 수를 구합니다.

 

get

getMul을 통하여 얻은 두 수를 가지고 나눠 떨어지는지 확인합니다.

 

max = (현재 몸무게 + 기억 몸무게)

min = (현재 몸무게 - 기억 몸무게)

 

max + min = 2 * 현재 몸무게

max - min = 2 * 기억 몸무게

 

둘 다 2로 나누어 떨어지지 않으면 자연수 G가 나올 수 없기 때문에,

(max + min) % 2 == 0 && (max-min) % 2 == 0

가 필요하다.

 

현재 몸무게는 (max + min) / 2 로 구하면 된다.

 

 


코드

 

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
package TwoPointers;
 
import java.io.*;
import java.util.*;
 
public class BOJ1484 {
    static int atoi(String str) {
        return Integer.parseInt(str);
    }
    static int G;
    static ArrayList<Integer> al = new ArrayList<>();
    static StringBuilder sb = new StringBuilder();
    public static void main(String[] args) throws IOException {
        input();
        pro();
    }
 
    static void pro() {
        //G가 되는 자연수 곱을 구해야함.
        getMul();
        get();
 
        if(sb.length() == 0System.out.println(-1);
        else System.out.println(sb);
    }
 
    static void get() {
        for (int i = al.size()-1; i >=0; i -= 2) {
            int max = Math.max(al.get(i), al.get(i - 1));
            int min = Math.min(al.get(i), al.get(i - 1));
 
            if((max + min) % 2 == 0 && (max-min) % 2 == 0){
                sb.append((max+min) / 2).append("\n");
            }
        }
    }
 
    static void getMul() {
        int s = 1, e = G;
 
        while (s < e) {
            int val = s * e;
 
            if(val > G){
                e--;
            }
            else if(val < G){
                s++;
            }
            else{
                al.add(s);
                al.add(e);
                s++;
                e--;
            }
        }
    }
 
    static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
        G = atoi(br.readLine());
    }
}
 
cs

 

 

728x90