(Search title) Luo Gu small wooden stick

Links: a small wooden stick

The entire process is recorded it, I first think of direct search, because the data range, it was only 65, but I was too young, this seems to be the index level! !

Direct search is the main enumerate all the possible minimum length, then dfs (root not much left to fight, how long now, objective);

This time out if it does not really odd strange

Then thank the problem solution mechanism Los Valley again! qaq

Thank big brother @ Lin qaq

 1 #include<iostream>
 2 #include<cstdlib>
 3 using namespace std;
 4 const int N=70;
 5 int tong[N];
 6 int cnt;
 7 int ma,mi,sum;
 8 void dfs(int res,int s,int tar,int p)
 9 {
10     if(res==0)
11     {
12         cout<<tar;
13         exit(0);
14     }
15     if(s==tar)
16     {
17         dfs(res-1,0,tar,ma);
18     }
19     for(int i=p;i>=mi;i--)
20     {
21         if(tong[i]&&i+s<=tar)
22         {
23             tong[i]--;
24             dfs(res,s+i,tar,i);
25             tong[i]++;
26             if (s==0||s+i==tar)
27                 break;
28         }
29     }
30 }
31 int main(void)
32 {
33     std::ios::sync_with_stdio(false);
34     int n;
35     cin>>n;
36     for(int i=1;i<=n;i++)
37     {
38         int t;
39         cin>>t;
40         if(t<=50)
41         {
42             tong[t]++;
43             sum+=t;
44             ma=max(ma,t);
45             mi=min(mi,t);
46         }
47     }
48     int t=sum>>1;
49     for(int i=ma;i<=t;i++)
50     {
51         if(sum%i==0)
52         {
53             dfs(sum/i,0,i,ma);
54         }
55     }
56     cout<<sum;
57     return 0;
58 }

1, just up from the enumeration to sum / 2; because if the sum / 2 can not, then it only makes up a stick all the

2, began descending enumeration, so a little faster, because if you are short of it all with a chance of not so long spell on the big lot of answers

3, the memory stick with a barrel length, so to find a lot of convenience less than the current wooden stick, stick numerals are used also more convenient (minus directly like)

4, the most difficult point is that if the (current length is 0), or (just search through the current length plus the length equal to the target length) to exit, s == 0 means I've found over again from the beginning of the largest ( Here also found pure waste of time), then you no longer start from smaller than the maximum search of the necessary, if the current length plus another just found over a length equal to the length of the target then express my conjunction long pole to scrape together all failure (if successful exit the program), certainly did not get to go to a search of the necessary short stick

Guess you like

Origin www.cnblogs.com/greenofyu/p/12005915.html