第七届ACM山东省赛-B Fibonacci

Time Limit: 2000MS Memory limit: 131072K

题目描述

Fibonacci numbers are well-known as follow:
第七届ACM山东省赛-B Fibonacci_第1张图片
Now given an integer N, please find out whether N can be represented as the sum of several Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers.

输入

Multiple test cases, the first line is an integer T (T<=10000), indicating the number of test cases.
Each test case is a line with an integer N (1<=N<=109).

输出

One line per case. If the answer don’t exist, output “-1” (without quotes). Otherwise, your answer should be formatted as “N=f1+f2+…+fn”. N indicates the given number and f1, f2, … , fn indicating the Fibonacci numbers in ascending order. If there are multiple ways, you can output any of them.

示例输入

4
5
6
7
100

示例输出
5=5
6=1+5
7=2+5
100=3+8+89

题意:判断所给的数能不能由斐波那契数组成,如果能输出任意一种组成形式,不能输出-1。

思路:先打出斐波那契的表,然后暴力搜索。

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

LL a[100];

LL b[40];

int ans;

void Init()
{
    a[0] = 0;

    a[1] = 1; a[2] = 2;

    for(int i = 3;i<=47;i++)
    {
        a[i] = a[i-1]+a[i-2];
    }
}

bool dfs(LL u,int st,int num)
{
    if(u == 0) 
    {
        ans = num;

        return true;
    }

    if(st == 0) return false;

    for(int i = st;i>=1;i--)
    {
        if(u >= a[i])
        {
            b[num] = a[i];

            if(dfs(u-a[i],i-1,num+1))
            {
                return true;    
            }
        }
    }
    return false;
}

int main()
{
    Init();

    int T;

    LL n;

    scanf("%d",&T);

    while(T--)
    {
        scanf("%lld",&n);

        if(dfs(n,47,0))
        {
            printf("%lld=",n);

            for(int i = ans - 1;i >=0;i--)
            {
                if(i!=ans-1) printf("+");

                printf("%lld",b[i]);
            }
            printf("\n");
        }
        else printf("-1\n");
    }
    return 0;
}

你可能感兴趣的:(第七届ACM山东省赛-B Fibonacci)