搜索+剪枝。 /*Sticks Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 78763 Accepted: 17360 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 Source Central Europe 1995*/ #include <stdio.h> #include <stdlib.h> #include "string.h" #define MAX_STICK_NUM 64 int giStickNum; int gaiStick[MAX_STICK_NUM]; int gaiSum[MAX_STICK_NUM]; int StickLenCmp(const void *a,const void *b) { return *(int *)b - *(int *)a; } int SearchLen(int viFirstCall,int viTgtLen,int viCurLen,int viStartIndex,int viStickNum) { int iTgtLen = viTgtLen; int iLoop; int iLen = 0; int iReturn; for (iLoop = viStartIndex; iLoop < giStickNum; iLoop++) { if (viCurLen > gaiSum[iLoop]) { return 0; } if (0 != gaiStick[iLoop] && viCurLen >= gaiStick[iLoop] &&iLen != gaiStick[iLoop]) { iLen = gaiStick[iLoop]; gaiStick[iLoop] = 0; if (0 == viCurLen - iLen) { if (2 >= viStickNum) { return 1; } iReturn = SearchLen(1,viTgtLen,viTgtLen,0, viStickNum-1); if (1 == iReturn) { return 1; } } else { iReturn = SearchLen(0,viTgtLen,viCurLen - iLen,iLoop+1, viStickNum); if (1 == iReturn) { return 1; } } gaiStick[iLoop] = iLen; if (1 == viFirstCall) { return 0; } } } return 0; } int Sticksmain() { int iLoopStick; int iStickLen; int iReturn; int iStickLenSum; while(1) { scanf("%d",&giStickNum); if (0 == giStickNum) { break; } iStickLenSum = 0; for (iLoopStick = 0; iLoopStick < giStickNum; iLoopStick++) { scanf("%d",&gaiStick[iLoopStick]); iStickLenSum += gaiStick[iLoopStick]; } qsort(gaiStick,giStickNum,sizeof(int),StickLenCmp); iStickLen = gaiStick[0]; gaiSum[giStickNum-1] = gaiStick[giStickNum-1]; for (iLoopStick = giStickNum-2; iLoopStick >= 0; iLoopStick--) { gaiSum[iLoopStick] = gaiSum[iLoopStick+1] + gaiStick[iLoopStick]; } while (1) { if (0 == iStickLenSum%iStickLen) { if (1 < iStickLenSum/iStickLen) { iReturn = SearchLen(1,iStickLen,iStickLen,0,iStickLenSum/iStickLen); if (0 == iReturn) {/*fail*/ iStickLen++; continue; } } printf("%d/n",iStickLen); break; } iStickLen++; if (iStickLen > iStickLenSum) { break; } } } return 0; }