dfs+剪枝 poj1011
Sticks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 113547 | Accepted: 26078 |
问题描述
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
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
样例输出
6
5
#include<iostream> #include<cstring> #include<iomanip> #include<cmath> #include<algorithm> using namespace std; int vis[64]={0}; int is_end=0;//代表结束 int sum;//总长度 int n; //总数量 int len; int a[64]; bool com(int a,int b) { return a>b; } void dfs(int used_num,int now_len,int now_index)//已使用的木棒总数,目前的长度,目前木棒的编号 { if(is_end==1) return; if(now_len==len) { if(used_num==n) is_end=1; else dfs(used_num,0,0);//代表拼成一个原始长度的了,继续拼下一个 return; } else if(now_len==0) { while(vis[now_index]==1) now_index++; vis[now_index]=1; dfs(used_num+1,a[now_index],now_index+1); vis[now_index]=0; } else { for(int i=now_index;i<n;i++) { if(vis[i]==0&&now_len+a[i]<=len) { if(vis[i-1]==0&&a[i-1]==a[i])//前一个和这个大小一样,而且不是同一次的dfs,就跳过 :剪枝 continue; vis[i]=1; dfs(used_num+1,now_len+a[i],i+1); vis[i]=0;// 一定要有,在上面dfs没有找到以后,重新设置为没有访问过。 } } } return; } int main() { while(cin>>n&&n!=0) { sum=0; for(int i=0;i<n;i++) { cin>>a[i]; sum+=a[i]; } is_end=0; sort(a,a+n,com);//从大到小排列 for(len=a[0];len<=sum;len++)//从最大的棒到总长度枚举 { if(sum%len!=0) continue;//总长度一定是原始长度的整数倍 else { memset(vis,0,sizeof(vis)); dfs(0,0,0); if(is_end==1) break; } } cout<<len<<endl; } return 0; }