UVA10450 POJ1953 World Cup Noise【斐波那契數列】

World Cup Noise

Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 23379 Accepted: 10359

Description

Background
“KO-RE-A, KO-RE-A” shout 54.000 happy football fans after their team has reached the semifinals of the FIFA World Cup in their home country. But although their excitement is real, the Korean people are still very organized by nature. For example, they have organized huge trumpets (that sound like blowing a ship’s horn) to support their team playing on the field. The fans want to keep the level of noise constant throughout the match.
The trumpets are operated by compressed gas. However, if you blow the trumpet for 2 seconds without stopping it will break. So when the trumpet makes noise, everything is okay, but in a pause of the trumpet,the fans must chant “KO-RE-A”!
Before the match, a group of fans gathers and decides on a chanting pattern. The pattern is a sequence of 0’s and 1’s which is interpreted in the following way: If the pattern shows a 1, the trumpet is blown. If it shows a 0, the fans chant “KO-RE-A”. To ensure that the trumpet will not break, the pattern is not allowed to have two consecutive 1’s in it.

Problem
Given a positive integer n, determine the number of different chanting patterns of this length, i.e., determine the number of n-bit sequences that contain no adjacent 1’s. For example, for n = 3 the answer is 5 (sequences 000, 001, 010, 100, 101 are acceptable while 011, 110, 111 are not).

Input

The first line contains the number of scenarios.
For each scenario, you are given a single positive integer less than 45 on a line by itself.

Output

The output for every scenario begins with a line containing “Scenario #i:”, where i is the number of the scenario starting at 1. Then print a single line containing the number of n-bit sequences which have no adjacent 1’s. Terminate the output for the scenario with a blank line.

Sample Input

2
3
1

Sample Output

Scenario #1:
5

Scenario #2:
2

Source
TUD Programming Contest 2002, Darmstadt, Germany

問題鏈接UVA10450 POJ1953 World Cup Noise
問題簡述:構造一個01串,使得當中的1不相鄰,問長度爲n的串有多少中。
問題分析
    考慮以下的長度情況。
1.n=1,可以取的串爲0或1,結果爲2,即f(1) = 2
2.n=2,可以取的串爲00、01和10,結果爲3,即f(2) = 3
3.串長度爲n時,若最後字符爲0,那麼前面長度爲n-1串的結尾可以是0或1,即f(n-1)
4.串長度爲n時,若最後字符爲1,那麼前面長度爲n-1串的結尾只能是0,即f(n-2)
5.結合上述的3和4,f(n) = f(n-2)+f(n-1),也就是斐波那契數列。
    先打表,程序速度就快了。
程序說明:(略)
參考鏈接:(略)
題記:(略)

AC的C++語言程序如下:

/* UVA10450 POJ1953 World Cup Noise */

#include <iostream>
#include <cstdio>

using namespace std;

const int N = 51;
long long fib[N + 1];

int main()
{
    fib[1] = 2LL;
    fib[2] = 3LL;
    for(int i = 3; i <= N; i++)
        fib[i] = fib[i - 2] + fib[i - 1];

    int t, n;
    scanf("%d", &t);
    for(int k = 1; k <= t; k++) {
        scanf("%d", &n);

        printf("Scenario #%d:\n%lld\n\n", k, fib[n]);
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章