题意:给出两个01串,每个位的权重是斐波那契值,要求相加后的结果,并将它们都转化为不存在连续1的字符串。
题解:斐波那契+模拟
预处理斐波那契数列,然后将原串转化为十进制
n
u
m
num
num。接下来考虑如何转化。
已知原串位数不超过40位,可以知道上限为
f
[
41
]
f[41]
f[41],从上限往下遍历,若
n
u
m
num
num≥
f
[
i
]
f[i]
f[i],减去即可,这样就不会出现连续1,推一推就知道了。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int maxn = 44;
string a, b, x, y, z;
int f[maxn], numa, numb, numc, lx, ly, lz;
void init() {
f[0] = 1, f[1] = 2;
for (int i = 2; i < maxn; i++) f[i] = f[i - 2] + f[i - 1];
}
int tonum(string x) {
int len = x.length(), num = 0;
for (int i = len - 1; i >= 0; i--) {
num += x[i] == '1' ? f[len - i - 1] : 0;
}
return num;
}
string tostring(int num) {
string temp;
for (int i = maxn - 1; i >= 0; i--) {
if (num >= f[i]) {
num -= f[i];
temp += "1";
}
else if (temp != "") {
temp += "0";
}
}
if (temp == "") temp = "0";
return temp;
}
int main() {
init();
while (cin >> a >> b) {
numa = tonum(a);
numb = tonum(b);
numc = numa + numb;
x = tostring(numa);
y = tostring(numb);
z = tostring(numc);
lx = x.length();
ly = y.length();
lz = z.length();
cout << " ";
for (int i = 0; i < lz - lx; i++) {
cout << " ";
}
cout << x << endl;
cout << "+ ";
for (int i = 0; i < lz - ly; i++) {
cout << " ";
}
cout << y << endl;
cout << " ";
for (int i = 0; i < lz; i++) {
cout << "-";
}
cout << endl;
cout << " " << z << endl;
cout << endl;
}
return 0;
}