建立字典树,保存计算的结果,便于下次查找
#include<iostream>
#include<vector>
#include<string>
#include<type_traits>
#include<sstream>
#include<tuple>
#include<bitset>
#include<regex>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
struct node{
int id;
node *next[10];
node(){
id = -1;
for (int i = 0; i < 10; i++) next[i] = NULL;
}
};
void insert(node* root,string t,int id){
node* temp = root;
for (int i = 0; i < t.size(); i++){
int index = t[i] - '0';
if (temp->next[index] == NULL){
temp->next[index] = new node;
temp->next[index]->id = id;
temp = temp->next[index];
}
else{
temp = temp->next[index];
}
}
}
int query(node* root,string t){
node *temp = root;
for (int i = 0; i < t.size(); i++){
int index = t[i] - '0';
if (temp->next[index] == NULL) return -1;
temp = temp->next[index];
}
return temp->id;
}
string add(string a,string b){
int i = a.size() - 1;
int j = b.size() - 1;
int in = 0;
string result = "";
while (i >= 0 && j >= 0){
int temp = (a[i] - '0') + (b[j] - '0') + in;
in = temp / 10;
temp = temp % 10;
result += (temp + '0');
i--;
j--;
}
while (i >= 0){
int temp = (a[i] - '0') + in;
in = temp / 10;
temp = temp % 10;
result += (temp+'0');
i--;
}
while (j >= 0){
int temp = (b[j] - '0') + in;
in = temp / 10;
temp = temp % 10;
result += (temp+'0');
j--;
}
if (in) result += (in+'0');
reverse(result.begin(),result.end());
return result;
}
int main(){
node *root = new node;
insert(root, "0", 0);
insert(root, "1", 1);
string a = "0";
string b = "1";
for (int i = 2; i < 100000; i++){
string sum = add(a,b);
a = b;
b = sum;
if (sum.size() > 40) sum = sum.substr(0,40);
insert(root,sum,i);
}
int T;
cin >> T;
for (int i = 0; i < T; i++){
string aim;
cin >> aim;
cout << "Case #" << (i + 1) << ": ";
int res = query(root, aim);
if(res==-1)
cout<<"-1"<< endl;
else cout << (res - 1) << endl;
}
//system("pause");
return 0;
}