반응형

https://www.acmicpc.net/problem/9020


위의 링크의 문제를 토대로 만들어본 코드이다.(하지만 시간초과 코드, 추후 알고리즘 문제풀이 게시판에 개선후 수록예정)


정렬 방법은 다음과 같다.


Arrays.sort를 이용하여 기본적인 배열을 정렬 할 수 있고, 뒤의 인자 2개는 정렬 구간을 의미하고 있다.


또한 Collection.sort를 통해 벡터를 정렬 할 수 있는데 이때 compare 연산자를 class comp와 같이 구현하여 사용 할 수 있다.

(현재 pair를 정렬해보았다.)




소스 코드 : 


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
package Algorithm;
 
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Vector;
 
class pair {
    int a;
    int b;
}
class Eratosthenes {
    boolean []isPrime = new boolean[10001];
    int []arr = new int[10001];
    int idx;
    void init() {
        for(int i = ; i <= 10000; i ++)
            isPrime[i] = true;
        
        isPrime[0= isPrime[1= false;
        idx = 0;
        
        for(int i = 2; i * i <= 10000; i++) {
            if(isPrime[i])
                for(int j = i * i; j <= 10000; j += i) {
                    isPrime[j] = false;
                }
        }
        for(int i = ; i <= 10000; i++) {
            if(isPrime[i])
                arr[idx++= i;
            
        }
        Arrays.sort(arr, 0, idx);
    }
    void solve(int n) {
        Vector<pair> vc = new Vector<pair>();
        
        for(int i = ; i < idx; i ++) {
            for(int j = ; j < idx; j++) {
                if(arr[i] + arr[j] == n) {
                    pair pi = new pair();
                    if(arr[i] < arr[j]) {
                        pi.a = arr[i];
                        pi.b = arr[j];
                        vc.add(pi);
                    }
                    else {
                        pi.a = arr[j];
                        pi.b = arr[i];
                        vc.add(pi);
                    }
                }
            }
        }
        Collections.sort(vc, new comp());
 
        System.out.println(vc.elementAt(0).a + " " + vc.elementAt(0).b);
    }
}
class comp implements Comparator<pair> {
    public int compare(pair a, pair b) {
        return Math.abs(a.a - a.b) < Math.abs(b.a - b.b) ? -1;
    }
}
public class BOJ_9020 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        
        Eratosthenes era = new Eratosthenes();
        era.init();
        int tc = sc.nextInt();
        while(tc-- > 0) {
            int n = sc.nextInt();
            era.solve(n);
        }
    }
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
cs

반응형