網頁

2008年7月10日 星期四

【ACM】100 - The 3n + 1 problem

100 - The 3n + 1 problem
UVa Online Judge >> Browse Problem >> Problem Set Volumes >> Volumes I >> 100 - The 3n + 1 problem

題目:點我(建議使用FireFox瀏覽)

題目大意:

這題的目的是要求各位輸入兩個值 i & j ,這兩個值所形成的區間中的每一個數字都需做運算。
  做以下運算:1)譬如輸入n
        2)如果n為奇數,n=n*3+1
        3)如果n為偶數,n=n/2
       
     EX:運算值為22==>22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
     則運算答案為16。


在 i 到 j 的區間中每個樹都要經過這個運算,在這些運算出的結果中挑出一個最大值。列印輸出結果時在印一次題目,後面接著印最大值。



Sample input1 10
100 200
201 210
900 1000

Sample output1 10 20
100 200 125
201 210 89
900 1000 174

原始碼:C program

#include stdio.h
int calc_cycle_len(int num)
{
    int cycle_length=1;
   
    while(num!=1)
    {
        cycle_length++;
        if(num%2==1)
            num=num*3+1;
        else
            num/=2;
    }
   
    return cycle_length;
}
int main(void)
{
    int temp,i,Num1,Num2,cycle_length=0,max_cycLen=0;
   
    while(scanf("%d %d",&Num1,&Num2)!=EOF)
    {
        printf("%d %d ",Num1,Num2);
        max_cycLen=0;
        if(Num1>Num2)
        {
            temp=Num2;
            Num2=Num1;
            Num1=temp;       
        }
        for(i=Num1;i<=Num2;i++)
        {
            cycle_length=calc_cycle_len(i);
            if(cycle_length>max_cycLen)
                max_cycLen=cycle_length;
        }
        printf("%d\n",max_cycLen);
    }
    return 0;
}

※有哪裡不懂得可以MSN問我,如果有錯誤的地方,可以直接在底下回覆糾正我的錯誤。
END

2 則留言:

  1. 快樂希望與愛的分享家2008年7月11日 上午10:12

    會的...堅持到底...你會拿到研究所的畢業證書....雖然..拿到以後...可能跟我一樣都快忘了放那@@"....加油喔..祝福你...培剛http://blog.xuite.net/erickhera.tw/nomore

    回覆刪除
  2. 這樣是不行的,Brute force 方法只會exceed 3 秒鐘的time limit

    回覆刪除