POJ-1011

Sticks
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 95944   Accepted: 21585

Description

George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.

Input

The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.

Output

The output should contains the smallest possible length of original sticks, one per line.

Sample Input

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

Sample Output

6
5

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int sticks[70], visit[70];
int sum, originally;

int cmp(const void *a, const void  *b)
{
	return *(int *)b - *(int *)a;
}

int dfs(int now, int n, int need, int num)
{
	int last = -1;
	
	if (need == 0) {
		for (n = now; visit[n]; n++)
			;
		if (sticks[n] == -1) return 1;
		visit[n] = 1;
		if (dfs(n, n+1, originally-sticks[n], num-1))
			return 1;
		visit[n] = 0;
		return 0;
	}

	for (; sticks[n] != -1; n++) {
		if (!visit[n] && sticks[n] <= need && sticks[n] != last) {
			visit[n] = 1;
			if (dfs(now, n+1, need - sticks[n], num-1))
				return 1;
			visit[n] = 0;
			last = sticks[n];
			if (need - sticks[n] == 0)
				break;
		}
	}
	return 0;
}

int main()
{
    int i, n, ok;
    while (scanf("%d", &n), n) {
          sum = 0;
          memset(sticks, 0, sizeof(sticks));
		  memset(visit, 0, sizeof(visit));
          for (i = 0; i < n; i++) {
			  scanf("%d", &sticks[i]);
              sum += sticks[i];
          }
		  qsort(sticks, 51, sizeof(sticks[0]), cmp);
		  sticks[n] = -1;
		  ok = 0;
		  for (i = sticks[0]; i <= sum/2; i++) {
			  if (sum % i == 0) {
				  originally = i;
				  visit[0] = 1;
				  if (dfs(0, 1, originally-sticks[0], n-1)) {
					ok = 1;
					printf("%d\n", i);
					break;
				  }
			  }
		  }
		  if (!ok)
			  printf("%d\n", sum);
    }
}


發佈了69 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章