【问题标题】:Why is recursive solution faster than an iterative solution for this case?为什么在这种情况下递归解决方案比迭代解决方案更快?
【发布时间】:2019-11-25 14:08:40
【问题描述】:

我正在尝试解决这个问题https://www.spoj.com/problems/COINS/

但奇怪的是,我的迭代解决方案:

#include <iostream>
using namespace std;

int main() {
    int n;
    while(cin >> n){
        long long int dp[n+2];
        dp[0]=0;
        for(long long int i=1; i<=n; i++)
            dp[i]=max(dp[i/2]+dp[i/3]+dp[i/4], i);
        cout << dp[n] <<endl;
    }
    return 0;
}

得到一个 TLE,而这个(不是我的)的递归解决方案很快就被接受了:

#include <cstdio>
#include <map>
#include <algorithm>

using namespace std;

map<int, long long> dp;

long long f(int n){
    if(n==0) return 0;

    if(dp[n]!=0) return dp[n];

    long long aux=f(n/2)+f(n/3)+f(n/4);

    if(aux>n) dp[n]=aux;
    else dp[n]=n;

    return dp[n];
}

int main(){    
    int n;

    while(scanf("%d",&n)==1) printf("%lld\n",f(n));

    return 0;
}

不应该是相反的吗?我真的很困惑。

【问题讨论】:

  • 为什么在第一个例子中使用cin,在第二个例子中使用scanf?你怎么能期望将这两个版本与这样的差异进行比较?还有哪个编译器,有哪些设置?
  • 看起来循环解决方案甚至不正确。 1)它不初始化'dp',2)它不最大化分数的值。即 i/2 本身可以分成 3 个部分。递归做到了,循环没有。
  • 函数的定义在哪里:max()?
  • @user3629249 max() 是一个内置的 c++ 函数。
  • @Serge 循环解决方案给出了正确答案。但它也显示了一个 TLE。

标签: c++ recursion iteration dynamic-programming


【解决方案1】:

据我所知,迭代解决方案在 n 中是线性的,即 O(n) 而递归解决方案是 O(log_2 n )。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-22
    • 2020-06-07
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多