UVa 100 3n+1
解題策略
很多人的第一題ACM,老老實實按照題目指示做就沒問題。把計算cycle length抽出來作一個獨立的函數的話,程式會清晰很多。注意
這題有個隱陷阱,就是題目給的a,b值不一定是a小於b,也可能a大於b,十個人裡有九個半都是栽在這裡,請跑跑以下關鍵測資:1 10 結果應該印出 1 10 20
10 1 結果應該印出 10 1 20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* UVa 100 3n+1 | |
* Author: chchwy | |
* Last Modified: 2011.01.30 | |
* Tag: Brute Force | |
*/ | |
#include<cstdio> | |
#include<algorithm> | |
using namespace std; | |
int cycle_length(int n) | |
{ | |
int length = 1; | |
while (n != 1) | |
{ | |
if (n % 2) //odd | |
n = 3 * n + 1; | |
else //even | |
n = n / 2; | |
++length; | |
} | |
return length; | |
} | |
int main() | |
{ | |
int a, b; //two input | |
while (scanf("%d %d", &a, &b) == 2) | |
{ | |
int max_cycle = 0; // max cycle length | |
for (int i = min(a, b); i <= max(a, b); ++i) | |
{ | |
int tmp = cycle_length(i); | |
if (tmp > max_cycle) | |
max_cycle = tmp; | |
} | |
printf("%d %d %d\n", a, b, max_cycle); | |
} | |
return 0; | |
} | |
留言
張貼留言