【HDU - 1455】Sticks (dfs + 剪枝)
題干:
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 file 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 0Sample Output
6 5解題報告:
? ? ?這題顯然是需要優雅的剪枝的。去掉剪枝1會T,去掉剪枝2會280ms。這份代碼是參考的網絡,二分查找位置。其實這也可以優化一下,讓我們湊每一根的時候都是從上一根+1的地方開始選,然后湊新的一根的時候,從頭開始查找第一個vis不等于1的木棒,繼續遞歸就行了。這種方法就跟【HDU - 1518】Square?的處理方法其實就差不多了。
?
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> using namespace std; const int MAX=10010; int a[MAX],n; bool vis[MAX]; int sum; int div(int x) {int l=1,r=n;int mid = (l+r)/2;while(l<r) {mid=(l+r)/2;if(a[mid]>x) l=mid+1;else r=mid;}return l; } bool cmp(const int & a,const int & b) {return a>b; }bool dfs(int cnt,int len,int d) {if(cnt==sum/len) return 1;int pos = lower_bound(a+1,a+n+1,len-d,cmp) - a; for(int i=pos; i<=n; i++) {if(vis[i]) continue;if(d+a[i]<len) {vis[i]=1;if(dfs(cnt,len,d+a[i])) return 1;vis[i]=0;if(d==0) return 0;//剪枝1}else if(d+a[i]==len) {vis[i]=1;if(dfs(cnt+1,len,0)) return 1;vis[i]=0;return 0;//剪枝2}}return 0; }int main() {while(~scanf("%d",&n)) {if(n == 0) break;memset(vis,0,sizeof(vis));sum=0;for(int i=1; i<=n; i++) scanf("%d",a+i),sum+=a[i];sort(a+1,a+1+n,cmp);for(int i=a[1]; i<=sum; i++) {memset(vis,0,sizeof(vis));if(sum%i!=0) continue;if(dfs(0,i,0)) {printf("%d\n",i);break;}}}return 0; }?
總結
以上是生活随笔為你收集整理的【HDU - 1455】Sticks (dfs + 剪枝)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【HDU - 薛猫猫杯程序设计网络赛】【
- 下一篇: 【牛客 - 185D】星光晚餐(数论,结