每次碰到斐波那契数列的题必有一次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;
}