POJ 2116 Death to Binary? (斐波那契+模拟)

题意:给出两个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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值