Special subset sums: testing
Problem 105
Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
- S(B) ≠ S(C); that is, sums of subsets cannot be equal.
- If B contains more elements than C then S(B) > S(C).
For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because 65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfies both rules for all possible subset pair combinations and S(A) = 1286.
Using sets.txt (right click and "Save Link/Target As..."), a 4K text file with one-hundred sets containing seven to twelve elements (the two examples given above are the first two sets in the file), identify all the special sum sets, A1, A2, ..., Ak, and find the value of S(A1) + S(A2) + ... + S(Ak).
NOTE: This problem is related to Problem 103 and Problem 106.
题意:
特殊的子集和:检验
记S(A)是大小为n的集合A中所有元素的和。若任取A的任意两个非空且不相交的子集B和C都满足下列条件,我们称A是一个特殊的和集:
- S(B) ≠ S(C);也就是说,任意子集的和不相同。
- 如果B中的元素比C多,则S(B) > S(C)。
例如,{81, 88, 75, 42, 87, 84, 86, 65}不是一个特殊和集,因为65 + 87 + 88 = 75 + 81 + 84,而{157, 150, 164, 119, 79, 159, 161, 139, 158}满足上述规则,且相应的S(A) = 1286。
在4K的文本文件sets.txt(右击并选择“目标另存为……”)中包含了一百组包含7至12个元素的集合(文档中的前两个例子就是上述样例),找出其中所有的特殊和集A1、A2、……、Ak,并求S(A1) + S(A2) + … + S(Ak)的值。
题解:位运算枚举子集。
代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
private static boolean check (int [] arr)
{
Arrays.sort (arr);
int front = arr [0], back = 0;
for (int i = 1; i < (int)Math.ceil (arr.length / 2.); i++)
{
front += arr [i];
back += arr [arr.length - i];
if (front <= back) return false;
}
boolean [][] seen = new boolean [arr.length / 2 + 1][front + back];
outer : for (int i = 1; i < (1 << arr.length); i++)
{
int sum = 0, count = 0;
for (int j = 0; j < arr.length; j++)
{
if ((i & (1 << j)) > 0)
{
sum += arr [j];
count++;
if (count > arr.length / 2) continue outer;
}
}
if (seen [count][sum]) return false;
seen [count][sum] = true;
}
return true;
}
public static void main (String [] args) throws IOException {
long time = System.currentTimeMillis ();
BufferedReader in = new BufferedReader (new FileReader (new File ("E:\\Walker_ACM代码库\\Project Euler\\101-150\\105_sets.txt")));
String line = in.readLine ();
int sum = 0;
while (line != null) {
String [] a = line.split (",");
int [] arr = new int [a.length];
int s = 0;
for (int i = 0; i < a.length; i++) {
arr [i] = Integer.parseInt (a [i]);
s += arr [i];
}
if (check (arr)) sum += s;
line = in.readLine ();
}
System.out.println (sum);
System.out.println ("Time: " + (System.currentTimeMillis () - time) / 1000. + "s");
}
}