poj1011:Sticks

来源:互联网 发布:淘宝天猫美工 编辑:程序博客网 时间:2024/05/17 09:25

1011:Sticks

  • 查看
  • 提交
  • 统计
  • 提示
  • 提问
总时间限制: 
1000ms 
内存限制: 
65536kB
描述
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.
样例输入
95 2 1 5 2 1 5 2 141 2 3 40
样例输出
65
来源
Central Europe 1995
    #include<iostream>#include<cmath>#include<cstring>#include<algorithm>#include<iomanip>#include<queue>#include<stack>#include<vector>#include<set>#include<map>using namespace std;int stick[65];bool vis[65];int L,n,pre;bool cmp(int x,int y){return x>y;}bool dfs(int m,int l) //剩下m根木棒,当前要凑出长度为l的木棒 {if(m==0&&l==0)return true;if(l==0){l=L;pre=-1;}for(int i=pre+1;i<n;++i){if(vis[i])continue;if(i>0&&!vis[i-1]&&stick[i-1]==stick[i])continue;if(stick[i]<=l){vis[i]=true;pre=i;if(dfs(m-1,l-stick[i]))return true;vis[i]=false;if(l==stick[i]||l==L)return false;//如果当前要凑的木棒是第一根或最后一根,却无法凑出,那么之后无论如何也凑不出 }}return false;}int main(){while(cin>>n&&n){int sum=0;for(int i=0;i<n;++i){cin>>stick[i];sum+=stick[i];}sort(stick,stick+n,cmp);for(L=stick[0];L<=(sum>>1);++L){if(sum%L!=0)continue;pre=-1;memset(vis,0,sizeof(vis));if(dfs(n,L)){cout<<L<<endl;break;}}if(L>(sum>>1)){cout<<sum<<endl;}}return 0;}