import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Sticks {
static int len;
static int avg;
static int[] seq;
static boolean[] isV;
static int total;
public static void main(String[] args) throws FileNotFoundException {
// TODO
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
sc = new Scanner(new File("files/sticks"));
while (true) {
len = sc.nextInt();
if (len == 0)
break;
seq = new int[len];
total = 0;
for (int i = 0; i < len; i++) {
seq[i] = sc.nextInt();
total += seq[i];
}
if (len == 1) {
System.out.println(seq[0]);
} else if (len == 2) {
if (seq[0] == seq[1])
System.out.println(seq[0]);
else
System.out.println(seq[1]+seq[0]);
} else {
System.out.println(Splice());
}
}
}
private static int Splice() {
// TODO Auto-generated method stub
Qsort(0, len - 1, seq);
for (avg= seq[0]; avg< total; avg++) {
if (total % avg!= 0)
continue;
isV = new boolean[len];
if (dfs(0, 0, 0))
break;
}
return avg;
}
private static boolean dfs(int n, int p, int num) {
// TODO Auto-generated method stub
if (avg* num == total)
return true;
for (int i = p; i < len; i++) {
if (isV[i] || (i != 0 && !isV[i - 1] && seq[i] == seq[i - 1]))
continue;
if (n + seq[i] == avg) {
isV[i] = true;
if (dfs(0, 0, num + 1))
return true;
isV[i] = false;
//因已排好序,若当前完成枝不可用,则后方枝也不可用,
//再往后选也不过是之前选过的子集
//故直接返回false
return false;
} else if (n + seq[i] < avg) {
isV[i] = true;
if (dfs(n + seq[i], i + 1, num))
return true;
isV[i] = false;
//判断是否为当前可用最大枝,
//若是,证明该枝永远也不可匹配成功,
//故直接返回false
if (n == 0)
return false;
}
}
return false;
}
private static void Qsort(int l, int r, int[] ss) {
// TODO Auto-generated method stub
if (l < r) {
int key = ss[r];
int i = l;
int j = r;
while (i < j) {
while (i < j && ss[i] > key)
i++;
ss[j] = ss[i];
while (i < j && ss[j] <= key)
j--;
ss[i] = ss[j];
}
ss[j] = key;
Qsort(l, j - 1, ss);
Qsort(j + 1, r, ss);
}
}
}
sample input:
2
10 12
9
15 4 1 11 3 2 8 8 8
1
20
45
15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8 15 3 2 11 4 1 8 8 8
15 3 2 11 4 1 8 8 8
12
1 1 2 2 2 3 3 3 3 3 3 4
46
40 37 32 10 47 4 42 56 61 23 59 36 27 16 16 37 26 19 14 29 31 58 51 32 63 28 11 25 12 15 39 42 46 43 11 19 53 17 39 21 45 44 8 23 51 55
58
57 6 44 4 16 35 54 9 32 23 43 55 46 41 8 41 55 44 31 59 57 58 59 29 53 30 3 39 52 17 32 45 8 40 34 18 20 11 32 33 14 41 31 25 4 42 54 9 29 37 47 29 34 20 47 56 61 5
26
3 64 18 49 4 40 18 61 50 36 17 49 8 17 62 11 24 8 36 59 34 26 28 7 37 26
27
15 3 2 4 11 1 8 8 8 15 3 2 4 11 1 8 8 8 15 3 2 4 11 1 8 8 8
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
5
20 20 20 20 20
0
sample output:
22
20
20
20
6
89
89
99
20
6
5
20
这是一个Java程序,用于解决将一定数量的棍子通过拼接形成等长组的问题。程序读取输入文件,根据棍子长度计算可能的组合,并输出最优解。涉及排序、递归搜索等算法。
1508

被折叠的 条评论
为什么被折叠?



