hdu 1145(Sticks) DFS剪枝
2024-09-08 05:31:02
Sticks
Problem DescriptionGeorge 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.InputThe 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.OutputThe output file contains the smallest possible length of original sticks, one per line.Sample Input95 2 1 5 2 1 5 2 141 2 3 40Sample Output65
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 100;
int n;
int s[N];
int v[N];
int t, length; //个数 长度
bool cmp(int a, int b){
return a > b;
}
bool dfs(int k, int len, int pos){ //第k根 第k跟长度 下标 //程序出口
if(k == t) return true; // 进来的时候肯定是 k = t, len = 0, pos = ? 最后一根的长度肯定是刚好等于 length !! if(len == length) return dfs(k+1, 0, 0); //拼接下一根 for(int i = pos+1; i <= n; i++){
if(!v[i] && len+s[i] <= length){
v[i] = 1;
if(dfs(k, len+s[i], i)) return true; //这种情况可以 下面的就不用看了
v[i] = 0; // len+s[i] 这种情况不行
if(len == 0) return false; //拼接第 k 跟木棒的 第一节的时候 不能拼成 length return false
while(s[i] == s[i+1]){ //相同的就不用看了
i++;
}
}
}
return false;
}
int main(){
while(~scanf("%d", &n) && n){
int sum = 0;
for(int i = 1; i <= n; i++){
scanf("%d", &s[i]);
sum += s[i];
}
sort(s+1, s+1+n, cmp); //降序
for(int i = s[1]; i <= sum; i++){
if(sum%i == 0){
memset(v, 0, sizeof v);
length = i;
t = sum / i; //组成的木棒个数
if(dfs(1, 0, 0)){//当前木棒数, 当前木棒数的长度, 下标
printf("%d\n", i);
break;
}
}
}
}
return 0;
}
最新文章
- BNUOJ 26475 Cookie Selection
- 我常用的iphone开发学习网站[原创]
- tensorflow elu函数应用
- 关于input内容改变的触发时间
- asp.net core 系列 2 启动Startup类介绍
- LINUX常见性能监控工具总结
- MySQL Hardware--Linux 文件句柄限制
- Ubuntu 18.1远程登录服务器--ssh的安装
- plsql developer无法识别32位oracle问题如何解决?
- 2017.5.11 MapReduce运行机制
- SqlServer 中 for xml path 相关
- mysql 数据范围总结
- Linux TCP/IP 连接查看和问题解决
- windows server 2008/2012安装PostgreSQL过程及问题总结
- nginx应用编译安装
- java8新特性视频、spring4.0视频讲解,javaee基础知识讲解等网址汇总
- href中使用相对路径访问上级目录的方法
- spring-boot启动注解@EnableAutoConfiguration
- vue框架组件之父子组件之间的通信
- Resharper安装及激活--转载