poj1011



package work;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main1011 {
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(“src/1011.txt”));
    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);
    }
}

}

、、input

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
2
1 1
2
1 3
0

、、output

6
5
1
4

点赞