poj 1207 The 3n + 1 problem

来源:互联网 发布:周扬青 淘宝直播 编辑:程序博客网 时间:2024/05/21 08:36

//poj 1207 The 3n + 1 problem
/*
照做就对了,把答案先算好,然后每次回答查询就行了。我用的是线段树,很快,0MS解决!
*/
#include <iostream>
#include <algorithm>

using namespace std;

struct node
{
       int l,r,max;
}ltree[100000];

int a[10001];
int cal(int n)
{
     int ans=1;
     while (1){
           if (n==1) break;
           if (n%2) n=3*n+1;
           else n>>=1;
           ++ans;
     }
     return ans;
}

void build(int root,int l,int r)
{
     ltree[root].l=l,ltree[root].r=r;
     if (l==r) {
               ltree[root].max=a[l];
               return ;
     }
     int mid=(l+r)>>1;
     build(root<<1,l,mid);
     build((root<<1)+1,mid+1,r);
     ltree[root].max=max(ltree[root<<1].max,ltree[root*2+1].max);
    
}

int query(int root,int l,int r)
{
    if (ltree[root].l==l && ltree[root].r==r) return ltree[root].max;
   
    int mid=(ltree[root].l+ltree[root].r)>>1;
    if (r<=mid) return query(root<<1,l,r);
    else if (l>mid) return query((root<<1)+1,l,r);
    else return max(query(root<<1,l,mid),query((root<<1)+1,mid+1,r));
}
int main()
{
    for (int i=1;i<=10000;i++) a[i]=cal(i);
    build(1,1,10000);
    int l,r;
    while (scanf("%d%d",&l,&r)!=EOF)
    {
          printf("%d %d %d/n",l,r,l<r?query(1,l,r):query(1,r,l));
    }
    system("pause");
    return 0;
   
}

原创粉丝点击