-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP046_SWEA3234_준환이의양팔저울.java
80 lines (62 loc) · 1.84 KB
/
P046_SWEA3234_준환이의양팔저울.java
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
// 순열
public class P046_SWEA3234_준환이의양팔저울 {
static int[] weight;
static boolean[] permIsSelected, subsetIsSelected;
static int N;
static int total;
static int[] numbers;
static int count;
static void perm(int cnt) {
if (cnt == N) {
subset(0, 0, 0);
return;
}
// 순열
for (int i = 0; i < weight.length; i++) {
// 중복체크 필요함
if(permIsSelected[i]) continue;
// 해당 수 선택
numbers[cnt] = weight[i];
permIsSelected[i] = true;
// 다음 순열 찾기
perm(cnt+1);
permIsSelected[i] = false;
}
}
static void subset(int index, int leftSum, int rightSum) {
// 오른쪽을 왼쪽이랑 비교
// 오른쪽은 왼쪽보다 크지 않다.
if (rightSum > total / 2) return;
if (index == N) {
count++;
return;
}
// 원소 선택
subsetIsSelected[index] = true;
if (rightSum + numbers[index] <= leftSum) subset(index + 1, leftSum, rightSum + numbers[index]);
subsetIsSelected[index] = false;
subset(index + 1, leftSum + numbers[index], rightSum);
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int t = 1; t <= T; t++) {
N = Integer.parseInt(br.readLine());
String[] line = br.readLine().split(" ");
weight = new int[N];
permIsSelected = new boolean[N];
subsetIsSelected = new boolean[N];
numbers = new int[N];
count = 0;
for (int i = 0; i < line.length; i++) {
int value = Integer.parseInt(line[i]);
weight[i] = value;
total += value;
}
perm(0);
System.out.println("#" + t+ " " + count);
}
}
}