洛谷 #2580. 于是他错误的点名开始了

本文介绍了一种使用字典树(Trie)来实现高效点名系统的方法,能够快速判断点名是否存在、是否重复及合法性。通过字典树的数据结构,可以优化查找过程,避免重复点名,确保点名的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

判断点名错误、合法、重复

题解

字典树

调试记录

#include <cstdio>
#include <cstring> 
#define maxn 1000005

using namespace std;

struct node{
	bool vis, exist;
	int next[26], cnt;
}tree[maxn];

int n, m, tot = 0;
char s[maxn];

void insert(){
	int l = strlen(s + 1);
	int last = 1;
	
	for (int i = 1; i <= l; i++){
		if (tree[last].next[s[i] - 'a'] == 0){
			tot++;
			tree[tot].cnt = tot;
			tree[last].next[s[i] - 'a'] = tot;
			last = tot;
		}
		else last = tree[last].next[s[i] - 'a'];
		if (i == l) tree[last].exist = true;
	}
}

int search(){
	int l = strlen(s + 1);
	int last = 1;
	
	for (int i = 1; i <= l; i++){
		if (tree[last].next[s[i] - 'a'] == 0) return 0;
		last = tree[last].next[s[i] - 'a'];
	}
	if (!tree[last].exist) return 0;
	if (tree[last].vis) return 2;
	tree[last].vis = true;
	return 1;
}

int main(){
	scanf("%d", &n);
	for (int i = 1; i <= n; i++){
		scanf("%s", s + 1);
		insert();
	}
	scanf("%d", &m);
	for (int i = 1; i <= m; i++){
		scanf("%s", s + 1);
		int res = search();
		if (res == 0) printf("WRONG\n");
		if (res == 1) printf("OK\n");
		if (res == 2) printf("REPEAT\n");
	}
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值