Fibonacci of the 7th ACM College Student Programming Competition in Shandong Province

Title:

Fibonacci sequence, give you a number n, ask you if you can get it by adding Fibonacci numbers, if you can, output the addition expression, if not, output -1

analyze:

Input
4
5
6
7
100
Output  
5=5
6=1+5
7=2+5
100=3+8+89

n is at most 10 9 , simply typed a table and found that the 45 items of the Fibonacci sequence exceeded 10 10 , the big water problem.
Play the table, start from the first item greater than n, and add it forward. If the sum is greater than n, it will not be marked, and if it is less than n, it will be marked as available until the sum is equal to n, and then search the marked array in positive order, and output it. . In addition, set a flag. If it is not equal to n until the end, modify the flag and output -1;

Code:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <algorithm>
#include <queue>
#include <map>
#define ll long long;
using namespace std;
const int maxn = 40+5;
const int mod = 1e9;
int num[maxn];
bool flag[maxn];
int cnt = 0;
void init(){
    num[1] = 1;
    num[2] = 2;
    for(int i = 3; i < 45;i++){
        num[i] = num[i-1]+num[i-2];
    }
}
int main(){
    std::ios::sync_with_stdio(false);
    init();
    int T;cin>>T;
    while(T--){
        memset(flag,false,sizeof(flag));
        int n; cin>>n;
        cout<<n<<"=";
        int k = 0;
        for(int i = 1; i < 45;i++){
            if(n < num[i]){
                k = i - 1;
                break;
            }
        }
        int sum = num[k];
        //cout<<num[k]<<" "<<k<<endl;
        flag[k] = true;
        if(sum == n){
            cout<<n<<endl;
            continue;
        }
        bool ff = false;
        for(int i = k - 1;i > 0;i--){
            if(sum + num[i] > n){
                continue;
            }
            else if(sum + num[i] < n){
                flag[i] = true;
                sum += num[i];
            }
            else{
                flag[i] = true;
                ff = true;
                break;
            }
        }
        if(!ff){
            cout<<-1<<endl;
        }
        else{
            bool li = true;
            for(int i = 0; i < maxn;i++){
                if(flag[i] && li){
                    cout<<num[i];
                    li = false;
                    continue;
                }
                if(flag[i] && !li){
                    cout<<"+"<<num[i];
                }
            }
        }
        cout<<endl;

    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325402353&siteId=291194637