NOJ1113 Fibonacci number Application Simulation
Description
Do you know the Fibonacci number? The following is a definition of it:
F1 = 1
F2 = 2
Fn + 1 = Fn + Fn-1, here n> 1
Each positive integer x can be written to the sum of different Fibonacci numbers, which means that there are numbers k and numbers b1, b2 ,..., Bk, so that x = b1 * F1 +... + Bi * Fi +... + Bk * Fk, where bk = 1 and bi (1 ≤ I <k) are 0 or 1. In short, we can write: B (x) = (bk, bk-1 ,..., B1 ). To make the representation unique, we require for all I> 1, bi * bi-1 = 0.
Using the Fibonacci number, we can convert the kilometer unit Distance x to the corresponding mile unit distance y. First, use the Fibonacci system to represent B (x) and write down x. Next, move the number in B (x) to the right (Delete the last digit) to obtain B (y ). Third, calculate the total number from B (y) to calculate y.
For example, the number 42 is represented as: (,) in the Fibonacci system ). Step 2: Right Shift to get (, 0 ). Step 3: calculate 0*1 + 0*2 + 0*3 + 1*5 + 0*8 + 0*13 + 1*21 = 26.
Next, write a program to convert the kilometer into a mile based on the above algorithm.
Input
Enter the first line containing t, the number of distances to be converted (0
Output
For each x km distance, the calculated y miles are output.
Sample Input
5
42
100
180
300
360
Sample output
26
62
111
185
222
Ideas
Simulate .... I originally wanted to use the conversion formula to set it up. I found that there was an error with the question =
Code
#include
#include
#include #include
using namespace std;const int maxn = 23;int f[maxn];int n;bool used[maxn];int main(){ f[1] = 1; f[2] = 2; for(int i = 3 ; i < maxn ; i ++) f[i] = f[i-1]+f[i-2]; int t; scanf("%d",&t); while(t--) { scanf("%d",&n); int pt; fill(used,used+maxn,false); for(pt = 1 ; pt < maxn ; pt ++) { if(f[pt] > n) break; } used[pt-1] = true; int tmp = f[pt-1]; for(int i = pt-2 ; i >= 1 ; i --) { if(tmp == n) break; if(used[i+1]) { continue; }else { if(f[i]+tmp <= n) { tmp += f[i]; used[i] = true; } } } int ans = 0; for(int i = 2 ; i < maxn ; i ++) { if(used[i]) ans += f[i-1]; } printf("%d\n",ans); } return 0;}