uva 763 Fibinary Numbers

来源:互联网 发布:他趣是个什么软件 编辑:程序博客网 时间:2024/05/29 14:33


  Fibinary Numbers 

The standard interpretation of the binary number 1010 is 8 + 2 = 10. An alternate way to view the sequence ``1010'' is to use Fibonacci numbers as bases instead of powers of two. For this problem, the terms of the Fibonacci sequence are: 

\begin{displaymath}1, 2, 3, 5, 8, 13, 21 , \dots\end{displaymath}


Where each term is the sum of the two preceding terms (note that there is only one 1 in the sequence as defined here). Using this scheme, the sequence ``1010'' could be interpreted as$1 \cdot 5 + 0 \bullet 3 + 1 \bullet 2 + 0 \bullet 1 = 7$. This representation is called a Fibinary number.


Note that there is not always a unique Fibinary representation of every number. For example the number 10 could be represented as either 8 + 2 (10010) or as 5 + 3 + 2 (1110). To make the Fibinary representations unique, larger Fibonacci terms must always be used whenever possible (i.e. disallow 2 adjacent 1's). Applying this rule to the number 10, means that 10 would be represented as 8+2 (10010).

Input and Output 

Write a program that takes two valid Fibinary numbers and prints the sum in Fibinary form. These numbers will have at most 100 digits.

In case that two or more test cases had to be solved, it must be a blank line between two consecutive, both in input and output files.

Sample Input 

1001011000010001000010000

Sample Output 

10100100000100100



Miguel Revilla 
2000-12-30




题目大意:给你两串数字,已斐波那契数列表示,从右往左 第k 位 的 权值为 f[k] ,求两串数字的和,要求相邻两个数字不能都为1,用斐波那契数列表示。

解题思路:利用两个性质 (1) 2*a[k]=a[k+1]+a[k-2] ,(2) a[k]=a[k-1]+a[k-2],模拟位运算,第k位如果>=2 利用性质(1),如果相邻两位都为1,利用性质(2),直到做到满足要求为止。



#include <iostream>#include <string>#include <algorithm>using namespace std;string rev(string st){    int len=st.length();    for(int i=0;i<len/2;i++){        swap(st[i],st[len-i-1]);    }    return st;}void computing(string a,string b){    if(a.length()<b.length()) swap(a,b);    a=rev(a);b=rev(b);    for(int i=0;i<b.length();i++) a[i]=a[i]+b[i]-'0';    //cout<<a<<endl;    bool flag=true;    while(flag){        flag=false;        for(int i=0;i<a.length();i++){            while(a[i]>='2'){                flag=true;                a[i]-=2;                if(i+1<a.length()) a[i+1]++;                else a.push_back('1');                if(i-2>=0) a[i-2]++;                else if(i-2==-1) a[i-1]++;            }        }        for(int i=0;i<a.length();i++){            if(a[i]=='1' && i+1<a.length() ){                if(a[i+1]=='1'){                    a[i]--;                    a[i+1]--;                    flag=true;                    if( i+2<a.length() ) a[i+2]++;                    else a.push_back('1');                }            }        }    }    a=rev(a);    cout<<a<<endl;}int main(){    int casen=0;    string a,b;    while(cin>>a>>b){        if(casen>0) cout<<endl;        computing(a,b);        casen++;    }    return 0;}


4 1