FZU 1961 凯撒密码II HDU 1251(字典树)

本文解析了FZU1961凯撒密码II及HDU1251两道ACM竞赛编程题,通过构建特定的数据结构实现字符串的高效查询与插入。介绍了程序的主要逻辑与实现细节。

FZU 1961 凯撒密码II

http://acm.fzu.edu.cn/problem.php?pid=1961


#include <stdio.h>

struct node{
	node * child[27];
	int value;		
}* root = new node();

//node * root = new..
void add_string(char * str, int num)
{
	node * next = root;
	while(*str)
	{
		if(next->child[*str-'a'] == NULL)		
			next->child[*str-'a'] = new node();
			
		next = next->child[*str-'a'];		
		++str;
	}
	next->value = num;
}

int query(char * str)
{
	node * next = root;
	while(*str)
	{
		if(next->child[*str-'a'] == NULL)
			return -1;
		next = next->child[*str-'a'];
		++str;	
	}
	return next->value;
}

int main()
{
	//freopen("E:\\input.txt", "r", stdin);
	int m, val;
	char c[3], danci[10];
	scanf("%d", &m);
	while(m--)
	{
		scanf("%s", c);
		if(c[0] == 'A')
		{
			scanf("%s %d", danci, &val);
			add_string(danci, val);
		}
		else
		{
			scanf("%s", danci);
			printf("%d\n", query(danci));
		}
	}
	return 0;
}

HDU1251

http://acm.hdu.edu.cn/showproblem.php?pid=1251

#include <iostream>
using namespace std;

struct node{
	node * child[27];
	int sum;	//前缀数 
	node(){ memset(child, 0, sizeof(child)); sum = 0;}
}* root = new node();

//node * root = new..
void add_string(char * str)
{
	node * next = root;
	while(*str)
	{
		if(next->child[*str-'a'] == NULL)		
			next->child[*str-'a'] = new node();
			
		next = next->child[*str-'a'];
		(next->sum)++;
		++str;
	}
}

int query(char * str)
{
	node * next = root;
	while(*str)
	{
		if(next->child[*str-'a'] == NULL)
			return 0;
		next = next->child[*str-'a'];
		++str;	
	}
	return next->sum;
}
int main()
{
	//freopen("E:\\input.txt", "r", stdin); 	
	char str[12];
	while(gets(str))
	{
		if(str[0] != 0)
		{
			add_string(str);
		}
		else
			break;
	}
	while(gets(str))
	{
		cout << query(str) << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值