码迷,mamicode.com
首页 > 其他好文 > 详细

1011:Sticks(dfs)

时间:2020-04-02 11:44:59      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:false   输入   long   using   int   sub   current   dom   rac   

 

总时间限制: 
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.
样例输入
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
样例输出
6
5
来源
Central Europe 1995
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n,l;
 4 int lastN=-1;
 5 vector <int> length;
 6 int visit[1010];
 7 bool cmp(int a,int b) {
 8     return a>b;
 9 }
10 bool dfs(int r,int k) {
11     if(r==0&&k==0)return true;
12     if(k==0)k=l;
13     int startN=0;
14     if(k!=l)startN=lastN+1;
15     for(int i=startN; i<n; i++) {
16         if(!visit[i]&&length[i]<=k) {
17             if(i>0) {
18                 if(visit[i-1]==false&&length[i]==length[i-1])continue;
19             }
20             visit[i]=1;
21             lastN=i;
22             if(dfs(r-1,k-length[i]))return true;
23             else {
24                 visit[i]=0;
25                 if(length[i]==k||k==l)return false;
26             }
27         }
28     }
29     return false;
30 }
31 int main() {
32     int c,maxl=0;
33     while(cin>>n&&n!=0) {
34         maxl=0;
35         length.clear();
36         for(int i=0; i<n; i++) {
37             cin>>c;
38             length.push_back(c);
39             maxl+=length[i];
40         }
41         sort(length.begin(),length.end(),cmp);
42         for(l=length[0]; l<=maxl/2; l++) {
43             if(maxl%l)continue;
44             memset(visit,0,sizeof(visit));
45             if(dfs(n,l)) {
46                 cout<<l<<endl;
47                 break;
48             }
49 
50         }
51         if(l>maxl/2)cout<<maxl<<endl;
52     }
53 
54     return 0;
55 }

 

1011:Sticks(dfs)

标签:false   输入   long   using   int   sub   current   dom   rac   

原文地址:https://www.cnblogs.com/aiqinger/p/12618502.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!