project euler problem 14

来源:互联网 发布:8099端口是干嘛的 编辑:程序博客网 时间:2024/05/16 14:06

Longest Collatz sequence

Problem 14

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.


题意:找出1000000以内最大的符合题目的数……

思路:刚开始想用的是递归,但是发现时间不行啊,等了好久结果都没出来;本来想到了用记忆化方法,但是编错了,又找不出原因,后面看了下魏神的代码,才发现记忆化方法,自己还是用得不够熟……用做题练练才得……

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <vector>#include <queue>#include <set>#include <stack>#include <cmath>#include <map>#include <ctime>using namespace std;int a[11111111];int cmp(long long x){    if(x == 1) return 1;    if(x<10000000&&a[x]) return a[x];//记忆住前面的过程,后面就不会重复计算同一个数了    int tmp;  //记忆化常数变量    if(x&1)  tmp = cmp(x * 3 + 1) + 1;    else  tmp = cmp(x / 2) + 1;    if(x < 10000000) a[x] = tmp;    return tmp;}int main(){    int ans = 1;    for(int i = 1; i < 1000000; i++)    {        a[i] = cmp(i);        if(a[i] > a[ans]) ans = i;    }    cout << ans << endl;    return 0;}

原创粉丝点击