搜索题

给定一个数S,找任意个正整数a1,a2,…,an,使得它们的和恰好等于S,且它们的倒数之和与1的差不超过10^-6。 输出任意一种方案或者输出无解。 S<=65536

  既然是搜索,那最好是要剪枝。

  (1)为了防止重复,也为了好搜从小到大搜,从二开始搜。

  (2)如果倒数的最大值加当前值 小于1-le-6,return。

  (3)如果倒数的最小值加当前值 大于1+le-6 ,return.

#include<iostream>
#include<cstdio >
#include<queue>
#include<algorithm>
#include<cstring>
#include<math.h>
using namespace std;
int s;
int ans[70000];
double sep=0.000001;
void wout(int x)
{
    for(int i=1;i<=x;i++)
    printf("%d ",ans[i]);
    return ;
}
void dfs(int tot,double all,int x,int last)
{
    ans[x]=last;
    //剪枝
    if(tot==s&&fabs(all-1)<=sep)    {wout(x);exit(0);}
    if(all+1.0/last*(((s-tot)/last)+1)<1-sep)    return;
    if(all+1.0/(s-tot)>1+sep)    return ;
    for(int i=last;i<=s-tot;i++)
        dfs(tot+i,all+(double)(1.0/i),x+1,i); 
}
int main()
{
    cin>>s;
    dfs(0,0.0,0,2);
    return 0;
}
原文地址:https://www.cnblogs.com/CLGYPYJ/p/7225515.html