习题5-15 UVa12333-Revenge of Fibonacci(TLE)(需字典树知识)

每次碰到斐波那契数列的题必有一次TLE…修改了几版之后仍然是TLE,除了输出-1的情况外几乎都很快了。之后参考了别人的代码,就是这一篇:ACM手记。虽然看懂了做法,但是可能有些细节没顾及到,所以还是WA了。最后就算这道题TLE吧,因为更多人的做法是我还没接触的字典树,等学到了再回头来做。

题目链接:UVa 12333

最终版的TLE代码:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
//#include <fstream>
#include <map>
#include <set>
using namespace std;

vector<string> fibo;

string Add(const string& a, const string& b) {
	int i = a.length() - 1, j = b.length() - 1, carryIn = 0, sum;
	string s;
	while (i >= 0 || j >= 0) {
		sum = carryIn;
		if (i >= 0) sum += (int)(a[i] - '0');
		if (j >= 0) sum += (int)(b[j] - '0');
		s.push_back(sum % 10 + '0');
		carryIn = sum / 10; i--; j--;
	}
	if (carryIn)
		s.push_back(carryIn + '0');
	reverse(s.begin(), s.end());
	return s;
}
int Fibo(string s) {
	int n = s.length();
	string str;
	for (int i = 0; i < 100000; i++) {
		while (fibo.size() > i) {
			if (fibo[i].substr(0, n) == s)
				return i;
			i++;
		}
		if (i == 0 || i == 1)
			str = "1";
		else 
			str=Add(fibo[i-1],fibo[i-2]);
		if (str.substr(0, n) == s)
			return i;
		fibo.push_back(str);
	}
	return -1;
}
int main() {
	int T, count = 1;
	string str;
	//ofstream out("C:\\Users\\Acer\\Desktop\\1.txt");
	cin >> T;
	/*if (out.is_open()) {
		while (T--) {
			cin >> str;
			out << "Case #" << count++ << ": " << Fibo(str) << endl;
		}
	}*/
	while (T--) {
		cin >> str;
		cout << "Case #" << count++ << ": " << Fibo(str)<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值