UVa 100 3n+1

这道题,wa死我了!宇神要是不提醒我,我估计我还wa着呢!

题不难想,但是陷阱是不少!

首先,输入的i和j不一定是从小到大;其次,i和j的输出位置不可以调换;还有,ans和cnt还有f[N]最好是用longlong类型;最后,要注意一个f的大小,用f存储的时候,要判断一下下标是否越界,最大的tmp不能超过N!

AC实属不易,考虑问题要全面,清楚!

优化的后的代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
long long f[1000001];
int n, m;

int main()
{
    memset( f, -1, sizeof(f));
    while ( scanf("%d%d", &n, &m) != EOF ) {
        long long ans = 0;
        int s = min( n, m ), e = max(n, m);
        for ( int i = s; i <= e; ++i ) {
            if ( f[i] != -1 ) {
                ans = max( ans, f[i] );
                continue;
            }
            int tmp = i;
            long long cnt = 1;
            while ( tmp != 1 ) {
                if ( tmp % 2 ) tmp = ( tmp*3 ) + 1;
                else tmp /= 2;
                if ( tmp < 1000000 && f[tmp] != -1 ) {
                    cnt += f[tmp];
                    break;
                }
                cnt++;
            }
            f[i] = cnt;
            ans = max( cnt, ans );
        }
        printf("%d %d %lld\n", n, m, ans);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值