hdu 1032 The 3n + 1 problem(水题)

来源:互联网 发布:linux mv命令 复制 编辑:程序博客网 时间:2024/05/21 21:54

开一个10W+的数组直接暴力就可以了

我觉得可以在暴力的基础上优化下,用打表的方法

例如处理一个数a,在循环内计算过程中变为b,如果恰好b对应的次数计算过

则只需要把当前a的计算次数加上b对应的计算次数,跳出循环即可

但是发现暴力采用了0ms...

数据是有多弱啊!

就没有优化的心情了

代码如下:

#include <stdio.h>#include <algorithm>#define MAXN 1001000using namespace std;//int cnt[MAXN];int f(int x) {    int cnt = 0;    while(true) {        cnt++;        if(x == 1)            break;        if(x & 1) {            x = 3*x+1;        } else x = x/2;    }    return cnt;}int main(void) {    int a, b, ans, i;    while(scanf("%d%d", &a, &b) != EOF) {        printf("%d %d ", a, b);        if(a > b) {//这里有坑!            a ^= b;            b ^= a;            a ^= b;        }        ans = 0;        for(i=a; i<=b; ++i) {            ans = max(ans, f(i));        }        printf("%d\n", ans);    }    return 0;}


0 0