C++算法计算效率的提高

最近在做CF上的比赛题的时候,遇到一道暴力求解的题目,如下:

B. Perfect Number
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

We consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer.

Input

A single line with a positive integer k (1 ≤ k ≤ 10 000).

Output

A single number, denoting the k-th smallest perfect integer.

Examples
input
1
output
19
input
2
output
28
题目很简单,就是要找到第k个完美数,完美数就是各个数位上的数字之和为10的,比如19,28等。

我一开始想到的是暴力解法,直接遍历每一个数字,然后每遇到一个完美数就计数器+1,直到计数器加到k,说明遇到的是第k个完美数,然后输出即可。代码如下:

#include "bits/stdc++.h"
using namespace std;
#define FASTER ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
int main(){
    FASTER;
    int k,sum,m,p;
    long long  n;
    sum=n=m=0;
    cin>>k;
    while(m!=k){
        sum=0;
        n++;
        p=log(n)+1;
        for(int i=0;i<p;i++)
            sum+=(long long)(n/pow(10,i))%10;
        if(sum==10)
              m++;

    }
    cout<<n;
    return 0;
    }
然鹅,这个算法超时了,在遇到K值比较大的时候,它坏了。于是我搞了好久,妄图减小时间复杂度,但实在是能力有限,想不到好方法了,无奈之下,我向一位陌生的网友寻求帮助,他是在CF上和我同个“考场”的人,于是我向他索求代码,代码如下:

#include "bits/stdc++.h"
using namespace std;

typedef int i;
typedef long int l;
typedef long long int ll;
typedef float f;
typedef long double lf;
typedef char c;

#define FASTER ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)

int main(void) {
  FASTER;
  std::vector<ll> ans;
  for (ll i = 0; i < 10800101; i++) {
    ll temp = i;
    ll sum = 0;
    while(temp != 0) {
      sum += temp%10;
      temp = temp/10;
    }
    if(sum == 10) {
      ans.push_back(i);
    }
  }
  ll k;
  cin >> k;
  cout << ans[k-1];
  return 0;
}
嗯?他用的居然也是跟我一样的思路?奇了怪了,都是暴力破解,我的还比他稍稍好点,咋地我的就不能AC呢?之后我通过在比赛结束后,拿不同的代码多次提交,对比我和他的代码差距在哪。最终发现,差别就在于我调用了pow()函数,而他是直接用的除法迭代,难道pow()函数对时间复杂度有很大的影响,考虑到这道题目中要求的k的范围是1到10000,当k为10000的时候,完美数是10800101,是个八位数,于是我上网查了一下资料: https://www.cnblogs.com/zhanghuaye/p/5089947.html,这个博客的作者实验了一下对于八位数的迭代次数,使用乘法的效率是比用pow()函数高很多的。由此可见,对于大数据运算问题,使用乘法好于调用pow()函数。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值