c++ - 给定初始种群 x,达到所需种群 y 的最少步骤是什么

标签 c++ function population

给定初始种群 x 和确切的期望种群 y, 到达 y 的最少步数是多少 使用三个函数 A{x+1}、B{x+2}、C{x+x}

我的方法

#include<iostream>
using namespace std;

int fA (int x)
{
    return x+1;
}
int fB(int x)
{
    return x+2;
}
int fC(int x)
{
    return x+x;
}

int main()
{
    int s, n;
    cin>>s>>n;

    int counter=0;

    while(fC(s)<=n)
    {
        s=fC(s);
        counter++;
    }

    while(fB(s)<=n)
    {
        s=fB(s);
        counter++;
    }

    while(fA(s)<=n)
    {
        s=fA(s);
        counter++;
    }

    cout<<counter;

    return 0;
}

我认为首先从增长最快的函数开始,然后是其他函数的假设是错误的,

欢迎任何帮助。

最佳答案

一个问题是“最快”取决于x。例如,最初使用 x=0 时,x+x 不会增长太多,并且使用 x=1 时,最快的是 x+2,而不是x+x

我会使用直接完整搜索方法:

int min_steps(int x, int y) {
    std::set<int> active, seen;
    active.insert(x); seen.insert(x);
    int steps = 0;
    while (active.size() && active.find(y) == active.end()) {
        // `active` is the set of all populations that we can
        // reach in `steps` number of steps or less not greater
        // than the target value `y`.
        // The next set is computed by starting from every value
        // and applying every possible growth function.
        // `seen` is the set of all values we saw before to avoid
        // adding a value that has been checked before.
        steps++;
        std::set<int> new_active;
        for (std::set<int>::iterator i=active.begin(),e=active.end();
             i!=e; ++i) {
            for (int f=0; f<3; f++) {
                int z;
                switch(f) {
                    case 0: z = *i + 1; break;
                    case 1: z = *i + 2; break;
                    case 2: z = *i + *i; break;
                }
                if (z <= y && seen.find(z) == seen.end()) {
                    new_active.insert(z);
                    seen.insert(z);
                }
            }
        }
        active = new_active;
    }
    return active.size() ? steps : -1;
}

鉴于 x <= 1000 从 1 到 x 的步数图表的外观,我的疯狂猜测是解决方案有一个封闭形式:看起来不明显但不完全随机...

enter image description here

关于c++ - 给定初始种群 x,达到所需种群 y 的最少步骤是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22517715/

相关文章:

javascript - 为什么这个简单的 javascript 函数不能完成它应该做的事情?

c - recv() 函数标志,用于在一个字符串中获取 while 缓冲区 [windows C]

c - 为什么人口计数的输入参数必须是无符号的

c# - 无法添加到类对象中的列表

c++ - Opengl 中的纹理采样

c++ - Visual Studio 2013 不必要的语法错误

javascript - 菜单容器 div 淡入/淡出不起作用

performance - 在 PostgreSQL 中填充数据库

c++ - 调用变量方法的类方法

c++ - C/C++编译器可以报告结构成员偏移量吗