Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 152214 | Accepted: 36272 |
Description
Input
Output
Sample Input
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
Sample Output
6 5
The meaning of the question: Given the length stick[i] of n small sticks, it is known that the n small sticks were originally decomposed from several long wooden sticks (original sticks) of the same length. Find the smallest possible length of the original rod.
Ideas: dfs + pruning. Quite a classic topic, the focus is on the design of dfs pruning. Let’s talk about the specific implementation first: find the total length sumlen and the longest length max of the small stick, then the possible length of the original stick must be between max~sumlen, and then enumerate max~sumlen from small to large and can be divisible by sumlen The length of len, use dfs to find out whether all the small sticks can be pieced together into this length, if so, the first len is the answer.
The following is the key, which is the implementation of dfs and the design of pruning for this question:
1. Start with a small stick, use dfs to see if you can piece the stick into a length of len, if possible, use vis[i] to record the used stick, and then continue to start with another stick, And so on.
2. The lengths of the sticks are sorted from large to small, so this will not be explained.
3. If the current longest rod cannot be spelled into len length, then go back to the previous step and change the combination of the longest rod in the previous step (here, it cannot be all exit), and there is no need to continue searching.
4.最重要的,就是比如说17,9,9,9,9,8,8,5,2……如果当前最长小棒为17,它与第一个9组合之后dfs发现不能拼成len,那么17就不用和后面所有的9组合了,而直接和8开始组合。这个剪枝直接从TLE到16MS,很强大。
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int n,len,stick[70]; bool flag,visit[70]; bool cmp(int a,int b) { return a>b; } void dfs(int num,int clen,int cur)//num为当前已被用过的小棒数,cur为当前要处理的小棒 { if(flag) return ; if(clen==0)//当前长度为0,寻找下一个当前最长小棒 { int k=0; while(visit[k]) k++;//寻找当前第一个最长小棒 visit[k]=true; dfs(num+1,stick[k],k+1); visit[k]=false; return ; } if(clen==len)//当前长度为len,即又拼凑成了一根 { if(num==n) flag=true;//完成的标志 :所有的n根小棒都被用过了 else dfs(num,0,0); return ; } for(int i=cur;i<n;i++) { if(!visit[i]&&clen+stick[i]<=len) { if(!visit[i-1]&&stick[i]==stick[i-1]) continue; //最最最最重要的剪枝!!!!!不重复搜索 visit[i]=true; dfs(num+1,clen+stick[i],i+1); visit[i]=false; } } } int main() { while(cin>>n&&n) { int lensum=0; flag=false; for(int i=0;i<n;i++) { cin>>stick[i]; lensum+=stick[i]; } sort(stick,stick+n,cmp);//从大到小排序 for(len=stick[0];len<lensum;len++) { if(lensum%len==0)//枚举能被sum整除的长度 { memset(visit,0,sizeof(visit)); dfs(0,0,0); if(flag) break; } } cout<<len<<endl; } }