UVA 12333 - Revenge of Fibonacci

建立字典树,保存计算的结果,便于下次查找

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值