[洛谷P1120]小木棍 [数据加强版]
题目大意:有一些同样长的木棍,被切割成几段(长$\leqslant$50)。给出每段小木棍的长度,找出原始木棍的最小可能长度。
题解:dfs
C++ Code:
#include<cstdio> #include<cstdlib> int n,sum,max,min=0x3f3f3f3f,x; int num[100]; void dfs(int res,int sum,int tar,int now) { if (res==0){printf("%d\n",tar);exit(0);} if (sum==tar){dfs(res-1,0,tar,max);return;} for (int i=now;i>=min;i--) if (num[i]&&i+sum<=tar){ num[i]--; dfs(res,sum+i,tar,i); num[i]++; if (sum==0||sum+i==tar)break; } } int main() { scanf("%d",&n); for (int i=1;i<=n;i++) { scanf("%d",&x); if (x<=50){ num[x]++;sum+=x; if (x>max)max=x; if (x<min)min=x; } } int tmp=sum>>1; for (int i=max;i<=tmp;i++)if (sum%i==0)dfs(sum/i,0,i,max); printf("%d\n",sum); return 0; }