1. 程式人生 > >[UVA - 11636] Hello World! 題解

[UVA - 11636] Hello World! 題解

printf read span ret -1 bsp 16px logs col

此文為博主原創題解,轉載時請通知博主,並把原文鏈接放在正文醒目位置。

題目鏈接(vjudge):https://vjudge.net/problem/UVA-11636

題目大意:

你有一條“hello world!”,你想要通過復制/粘貼得到n條相同的語句。

例如你可以第一次復制得到2條,第二次復制得到4條...當然,你也可以不全復制,例如第二次復制得到3條。

給出多個n(以一個負數表示結束),對每個n,輸出最少需要復制多少次。0<n<10001。

樣例輸入:

2

10

-1

樣例輸出:

Case 1: 1

Case 2: 4

分析:

根據n的範圍可知答案不超過15.

事先計算出2^i的值,然後對每一個n,二分查找第一個恰好大於它的2^i的值對應的i。

AC代碼:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #include<cmath>
 6 
 7 inline void read(int &x)
 8 {
 9     char ch = getchar(),c = ch;x = 0;
10     while(ch < 
0 || ch > 9) c = ch,ch = getchar(); 11 while(ch <= 9 && ch >= 0) x = (x<<1)+(x<<3)+ch-0,ch = getchar(); 12 if(c == -) x = -x; 13 } 14 15 int n,cnt,ans,f[20]; 16 17 inline void init() 18 { 19 f[0] = 1,f[1] = 2; 20 for(int i = 2;i <= 18;++ i)
21 f[i] = f[i-1]*2; 22 } 23 24 int calc(int x) 25 { 26 int l = 1,r = 20,mid,Ans; 27 while(l <= r) 28 { 29 mid = (l+r)>>1; 30 if(f[mid] >= x) Ans = mid,r = mid-1; 31 else l = mid+1; 32 } 33 return Ans; 34 } 35 36 int main() 37 { 38 init(); 39 while(1) 40 { 41 read(n); 42 if(n < 0) break; 43 ++ cnt; 44 if(n == 0 || n == 1) printf("Case %d: %d\n",cnt,0); 45 else{ 46 ans = calc(n); 47 printf("Case %d: %d\n",cnt,ans); 48 } 49 } 50 return 0; 51 }

[UVA - 11636] Hello World! 題解