Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Java实现代码

Posted by 568720503 at 2012-07-04 14:15:21 on Problem 1011
import java.util.Scanner;

public class Main {

	static int[] sticks;
	static boolean[] visited;
	static int n;
	static int st;

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		while ((n = scan.nextInt()) != 0) {
			int sum = 0;
			sticks = new int[n];
			visited = new boolean[n];
			for (int i = 0; i < n; i++) {
				sticks[i] = scan.nextInt();
				sum += sticks[i];
			}
			quicksort(0, n - 1);
			boolean flag = false;
			for (int ini = sticks[0]; ini < sum; ini++) {
				if (sum % ini == 0 && dfs(0, 0, ini, 0)) {
					System.out.println(ini);
					flag = true;
					break;
				}
			}
			if (!flag) {
				System.out.println(sum);
			}
		}
	}

	static boolean dfs(int len, int s, int ini, int am) {
		if (am == n) {
			return true;
		}

		int sp = -1;

		for (int i = s; i < n; i++) {
			if (visited[i] || sticks[i] == sp) {
				continue;
			}
			visited[i] = true;
			if (len + sticks[i] < ini) {
				if (dfs(len + sticks[i], i, ini, am + 1)) {
					return true;
				} else {
					sp = sticks[i];
				}
			} else if (len + sticks[i] == ini) {
				if (dfs(0, 0, ini, am + 1)) {
					return true;
				} else {
					sp = sticks[i];
				}
			}
			
			visited[i] = false;

			if (len == 0) {
				return false;
			}
		}
		return false;
	}

	static void quicksort(int p, int r) {
		if (p < r) {
			int a = part(p, r);
			quicksort(p, a - 1);
			quicksort(a + 1, r);
		}
	}

	static int part(int p, int r) {
		int x = sticks[r];
		int i = p - 1;
		int j = p;
		for (; j < r; j++) {
			if (sticks[j] > x) {
				i++;
				int k = sticks[i];
				sticks[i] = sticks[j];
				sticks[j] = k;
			}
		}
		int k = sticks[i + 1];
		sticks[i + 1] = sticks[j];
		sticks[j] = k;
		return i + 1;
	}

}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator