HDOJ1032 The 3n+1 problem

来源:互联网 发布:linux网络监控工具 编辑:程序博客网 时间:2024/05/30 04:32
一道水题。。

Caution:1.题目中没有给出i,j的大小关系,所以要分I>=J和I<J讨论。

  2.注意到题中“Input”部分的提示:

The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.

You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j.

You can assume that no opperation overflows a 32-bit integer.

 也就是说运算过程中不会出现溢出。
但在实际调试中发现x=113383时,Find函数中出现了y的溢出,所以题目中给出的数据必不包含这个数。
越到后面,这样的数越密集。所以暴力算法也不会超时……
非暴力算法则是在暴力算法的基础上添加一个1000000的数组记录已出现过的情况,可减少部分时间。
下面是暴力算法。
第三种做法则是利用BFS。但BFS的空间要求较高,保守估计达到了5e8个数组空间,在内存小的评测机上不适用,故不给出。



#include "stdio.h" int Find(int x){    int i;    long long y;    y=x;    i=1;    while(y!=1){        if(y%2==0)y=y/2;else y=3*y+1;        i++;    }    return i;}int Search(int x,int y){    int i,maxi,k;    maxi=-1;    for(i=x;i<=y;i++){        k=Find(i);        if(maxi<k)maxi=k;    }    return maxi;}void Swap(int *i,int *j){int t;t=*i;*i=*j;*j=t;}int main(){int i,j;while(scanf("%d%d",&i,&j)!=EOF){if(i>j)printf("%d %d %d\n",i,j,Search(j,i));else printf("%d %d %d\n",i,j,Search(i,j));}return 0;}


0 0
原创粉丝点击