这道题,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); } }