Sticks UVA - 307(切木棍 线性区间dp,线性dp,区间思想。)
題目大意:將n節(jié)木棒接成m個長度相等的木條,要求木條的長度盡可能的短
Time limit? ? ?3000 ms
OS? ? ?Linux
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.?
Input?
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.?
Output?
The output should contains the smallest possible length of original sticks, one per line.?
Sample Input?
9?
5 2 1 5 2 1 5 2 1?
4?
1 2 3 4?
0?
Sample Output?
6?
5
1.按遞減順序搜索
2.剪枝: (1).原木棍的長度必須是所有木棍長度之和的約數(shù)
(2).搜索原木棍長度只需搜到sum/2 若前面還沒成功 答案就只能是sum了
(3).構(gòu)造一根原木棍的第一根小木棍必須是最長的
(4).2根長度相同的木棍沒必要重復(fù)搜索
#include<iostream> #include<algorithm> #include<string.h> using namespace std;int t,w[110],sum,book[110],flag; bool cmp(int a,int b) {return a>b; } void dfs(int step,int sum,int h,int l)/*step:遍歷過的棒,sum:棒變化的值,h: 從大到小遍歷棒 ,第幾個棒,l:原始棒的長度*/ {if(flag)return ;if(step==t){if(sum==0)flag=1;return ;}if(sum==0)/*棒的重新組合*/{for(int i=0;i<t;i++){if(book[i]==0){book[i]=1;dfs(step+1,l-w[i],i,l);book[i]=0;break;}}}else{for(int i=h+1;i<t;i++){if(book[i]==0&&sum>=w[i]){book[i]=1;dfs(step+1,sum-w[i],i,l);if(flag)return ;book[i]=0;while(i+1<t&&w[i]==w[i+1])i++;/*2根長度相同的木棍沒必要重復(fù)搜索*/}}}return ; } int main() {while(cin>>t&&t){sum=0;flag=0;int ant=-1;for(int i=0;i<t;i++){cin>>w[i];ant=max(ant,w[i]);sum+=w[i];}sort(w,w+t,cmp);int i;for(i=ant;i<=sum/2;i++){if(sum%i==0){memset(book,0,sizeof(book));dfs(0,0,0,i);if(flag)break;}}if(flag)cout<<i<<endl;elsecout<<sum<<endl;}return 0; }?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Sticks UVA - 307(切木棍 线性区间dp,线性dp,区间思想。)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 艾灸减肥灸哪个部位瘦得最快
- 下一篇: 针灸减肥的利弊是什么