Sticks
时间限制: 1 Sec 内存限制: 128 MB提交: 26 解决: 4
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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.
输入
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.
输出
The output should contains the smallest possible length of original sticks, one per line.
样例输入
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
样例输出
6 5
题意
有n个木棍,用这些木棍拼成m个一模一样的木棍,使得拼成的长度尽量小。
分析
DFS搜索没什么好说的,经典剪枝倒是不少。
1、枚举m,那么n个木棍的总长度一定整除m。
2、从大到小排序,每次从最大的开始选,dfs过程可以减少。
3、两根一模一样的木棍不需要重复判断。
4、如果一根木棍无法与其它木棍拼成所需长度,那么这个方案一定不可行,因为最终所有木棍都要被用上。
/// author:Kissheart /// #include<stdio.h> #include<algorithm> #include<iostream> #include<string.h> #include<vector> #include<stdlib.h> #include<math.h> #include<queue> #include<deque> #include<ctype.h> #include<map> #include<set> #include<stack> #include<string> #define INF 0x3f3f3f3f #define FAST_IO ios::sync_with_stdio(false) const double PI = acos(-1.0); const double eps = 1e-6; const int MAX=1e5+10; const int mod=1e9+7; typedef long long ll; using namespace std; #define gcd(a,b) __gcd(a,b) inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;} inline ll qpow(ll a,ll b){ll r=1,t=a; while(b){if(b&1)r=(r*t)%mod;b>>=1;t=(t*t)%mod;}return r;} inline ll inv1(ll b){return qpow(b,mod-2);} inline ll exgcd(ll a,ll b,ll &x,ll &y){if(!b){x=1;y=0;return a;}ll r=exgcd(b,a%b,y,x);y-=(a/b)*x;return r;} inline ll read(){ll x=0,f=1;char c=getchar();for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;for(;isdigit(c);c=getchar()) x=x*10+c-'0';return x*f;} //freopen( "in.txt" , "r" , stdin ); //freopen( "data.txt" , "w" , stdout ); int n,sum,len; int a[105],vis[105]; int cmp(int a,int b) { return a>b; } /// N:选了几根木棍 x:目前木棍的和 indx:数组开始的下标 int dfs(int N,int x,int indx) { if(N==n+1) return 1; for(int i=indx;i<=n;i++) { if(vis[i]) continue; if(x+a[i]<len) { vis[i]=1; if(dfs(N+1,x+a[i],i+1)) return 1; vis[i]=0; while(a[i]==a[i+1] && i+1<=n) i++;///两个一样的木棍,不用重复判断。 } else if(x+a[i]==len) { vis[i]=1; if(dfs(N+1,0,1)) return 1; vis[i]=0; return 0; ///如果当前木棍无法与其它木棍拼成所需木棍,那枚举的len一定不行。 } if(x==0) return 0; } return 0; } int main() { while(scanf("%d",&n) && n) { sum=0; for(int i=1;i<=n;i++) scanf("%d",&a[i]),sum+=a[i]; sort(a+1,a+1+n,cmp);///优先找长度大的减少递归。 int ans=0,i; for(i=n;i>=1;i--) { if(sum%i==0 && sum/i>=a[1]) { memset(vis,0,sizeof(vis)); len=sum/i; if(dfs(1,0,1)) { printf("%d ",len); break; } } } } return 0; }