poj1011Sticks(搜索+剪枝)
Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 145596 Accepted: 34453
Description
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
题意:现在有短枝参差不齐若干个,不知原长,不知原数量,求最短的原短枝长度(原短枝长度均相同)。
搜索,将所有短枝从大到小排序求出MAX,则能出现的原短枝len必是处在(MAX,sum)之间,然后从大到小枚举短枝,搜索其与剩下所有的短枝匹配,若出现能让sum%len为0的len,且能让搜出的匹配数u=n时,则输出当前len。
剪枝:剪除相邻长度相同且不能与前一len匹配的短枝,例如10,7,7,7,7 ,7,6,5。由于10与7匹配后并不能被sum%now_len=0,则将后面所有的相同的短枝跳过搜索。
#include<iostream>
#include<algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int n,a[110];
int vist[110];
int flag;
int cmp(int a,int b)
{
return a>b;
}
int len;
void dfs(int s,int now_len,int u)
{
if(flag)
return;
if(now_len==0)
{
int k=0;
while(vist[k])k++;
vist[k]=1;
dfs(s+1,a[k],k+1);
vist[k]=0;
return;
}
if(now_len==len)
{
if(s==n)
{
flag=1;
return;
}
else dfs(s,0,0);
return;
}
for(int i=u;i<n;i++)
{
if(!vist[i]&&now_len+a[i]<=len)
{
if(!vist[i-1]&&a[i]==a[i-1]) continue;
vist[i]=1;
dfs(s+1,now_len+a[i],i+1);
vist[i]=0;
}
}
return;
}
int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
int sum=0;
flag=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
}
sort(a,a+n,cmp);
for(len=a[0];len<sum;len++)
{
if(sum%len==0)
{
memset(vist,0,sizeof(vist));
dfs(0,0,0);
if(flag)break;
}
}
cout<<len<<endl;
}
return 0;
}
上一篇: Linux下批量kill多个进程的方法
下一篇: 编写Java的感悟
推荐阅读
-
poj1011Sticks(搜索+剪枝)
-
POJ1011 Sticks 深度优先搜索+剪枝
-
洛谷Function(P1464)记忆化搜索or记忆宏
-
web架构设计经验分享 博客分类: 网站架构 Web敏捷开发数据结构网页游戏搜索引擎
-
互联网创业越简单越容易成功 博客分类: 项目管理 互联网软件测试搜索引擎项目管理工作
-
简单题--700. 二叉搜索树中的搜索
-
分布式搜索elasticsearch集群监控工具bigdesk 博客分类: ElasticSearch 分布式搜索elasticsearch集群监控工具bigdesk監控
-
分布式搜索elasticsearch的5种分片查询优先级 博客分类: ElasticSearch 分布式搜索elasticsearch的5种分片查询优先级ElasticSearch
-
分布式搜索elasticsearch集群管理工具head 博客分类: ElasticSearch 分布式搜索elasticsearch集群管理工具head
-
对mencache和tokyocabinet缓存的一点点遐想 博客分类: 综合技术 TokyoCabinet搜索引擎算法框架