Sticks --dfs 剪枝
来源:互联网 发布:淘宝买家仅退款不退货 编辑:程序博客网 时间:2024/05/20 23:35
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
解题报告
还是太弱了,参考了别人的代码。
这个题体现了剪枝的重要性。剪一刀(加一个限定条件)计算过程可以减少若干倍。
#include<stdio.h>#include<string.h>#include<algorithm>#define MAX_N 70using namespace std;int a[MAX_N];bool vis[MAX_N];int goal,sum,N;bool dfs(int now,int head,int cnt){ if(goal*cnt==sum) return true; for(int i=head;i<N;i++){ if(vis[i]||(i&&!vis[i-1]&&a[i]==a[i-1])) continue; if(now+a[i]==goal){ vis[i]=true; if(dfs(0,0,cnt+1)) return true; return vis[i]=false; } if(now+a[i]<goal){ vis[i]=true; if(dfs(now+a[i],i+1,cnt)) return true; vis[i]=false; if(!now) return false; } } return false;}bool cmp(int x,int y){return x>y;}int main(){ while(scanf("%d",&N)&&N!=0){ sum=0;int M=-1; for(int i=0;i<N;i++){ scanf("%d",&a[i]); M=max(a[i],M); sum+=a[i]; } sort(a,a+N,cmp); memset(vis,0,sizeof(vis)); for(goal=M;goal<=sum;goal++) if(sum%goal==0&&dfs(0,0,0)) break; printf("%d\n",goal); } return 0;}
- POJ1011-Sticks DFS+剪枝
- poj1011 Sticks(dfs+剪枝)
- UVa307 - Sticks(DFS+剪枝)
- POJ1011 Sticks DFS+剪枝
- POJ1011 Sticks【DFS+剪枝】
- HDU1455 Sticks(DFS+剪枝)
- Sticks --dfs 剪枝
- poj1011 -- Sticks (DFS+剪枝)
- poj 1011Sticks(DFS +剪枝)
- POJ 1011 Sticks dfs + 剪枝
- PKU-1011 Sticks (DFS + 剪枝)
- HDU 1455 Sticks(DFS+剪枝)
- POJ 1011 Sticks DFS+剪枝
- poj 1011 Sticks -----dfs+剪枝
- POJ 1011 Sticks (DFS + 剪枝)
- POJ 1011 Sticks DFS 剪枝
- Sticks(DFS+剪枝+贪心)
- NYOJ-293 Sticks DFS+剪枝
- HDU1698 Just a Hook 线段树成段替换
- java设计模式之组合模式
- tcp为什么需要3次握手和3次握手的过程
- dfs走迷宫
- python优雅实现策略模式
- Sticks --dfs 剪枝
- java编程思想读书笔记--第四章 控制执行流程
- 用穷举法解决皇后问题
- Android 热修复 Tinker接入及源码浅析
- 反转单词顺序
- #21. DFA
- 用CSS画出三角形
- 写一个 iOS 复杂表单的正确姿势
- HDOJ(HDU).1015 Safecracker (DFS)