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;
}
本文解析了FZU1961凯撒密码II及HDU1251两道ACM竞赛编程题,通过构建特定的数据结构实现字符串的高效查询与插入。介绍了程序的主要逻辑与实现细节。
&spm=1001.2101.3001.5002&articleId=7750645&d=1&t=3&u=2829dd2693064e5b9cc3e8299ceae2d2)
368

被折叠的 条评论
为什么被折叠?



