zoukankan      html  css  js  c++  java
  • POJ 1207 The 3n + 1 problem

    水题,直接筛一下就好。只是须要注意输出。

    自己学校的渣OJ 的数据范围才叫大:All integers will be less than 10,000,000 and greater than 0.

    跑了1.7ms。时限2ms。


    POJ这道题数据范围是:All integers will be less than 10,000 and greater than 0.

    直接全部的删掉2个0。直接就0ms了。


    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<queue>
    using namespace std;
    bool v[100001];
    int a[100001];
    queue<int>q;
    int bfs()
    {
        memset(v,0,sizeof(v));
        memset(a,0,sizeof(a));
        q.push(1);v[1]=1,a[1]=1;
        while(1)
        {
            int i,tmp,ans;
            bool ok=0;
            while(!q.empty())
            {
            tmp=q.front(),q.pop();
            if((tmp-1)%3==0&&tmp>1&&((tmp-1)/3)&1)
            {
                ans=(tmp-1)/3;
                if(!v[ans]&&ans<100001)
                v[ans]=1,a[ans]=a[tmp]+1,q.push(ans),ok=1;
            }
                ans=tmp*2;
                if(!v[ans]&&ans<100001)
                v[ans]=1,a[ans]=a[tmp]+1,q.push(ans),ok=1;
            }
        if(!ok)break;
        }
        long long i,ans,tmp;
        for(i=1;i<100001;i++)
        {
    
            if(!v[i])
            {
                tmp=i;ans=0;
                while(1)
                {
                    if(tmp&1)
                    tmp=3*tmp+1,ans++;
                    else
                    tmp/=2,ans++;
                    if(tmp<100001&&a[tmp]!=0)break;
                }
                a[i]=a[tmp]+ans;
                v[i]=1;
            }
        }
    }
    int main()
    {
        int a1,a2,i,tmp;
        bfs();
        while(~scanf("%d%d",&a1,&a2))
        {
            bool ok=0;
            if(a1>a2)ok=1;
            tmp=max(a1,a2);
            a1=min(a1,a2),a2=tmp;
            tmp=0;
            for(i=a1;i<=a2;i++)
            tmp=max(tmp,a[i]);
            if(!ok)
            printf("%d %d %d
    ",a1,a2,tmp);
            else
            printf("%d %d %d
    ",a2,a1,tmp);
        }
    }


  • 相关阅读:
    #一点杂记
    《洛谷P3373 【模板】线段树 2》
    《Codeforces Round #681 (Div. 2, based on VK Cup 2019-2020
    《牛客练习赛72C》
    《hdu2819》
    《hdu2818》
    《Codeforces Round #680 (Div. 2, based on Moscow Team Olympiad)》
    《51nod1237 最大公约数之和 V3》
    对输入的单词进行排序
    快速排序
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4003178.html
Copyright © 2011-2022 走看看