字典树 —— 模板习题

模板:

struct Trie{
	static const int maxt = 1e7+5;
	int rt, id, tot, t[maxt][2];
	int cnt[maxt], val[maxt], end[maxt];
	inline int newnode(){
		++tot;
		t[tot][0] = t[tot][1] = 0;
		cnt[tot] = end[tot] = val[tot] = 0;
		return tot;
	}
	inline void init(){
		tot = 0;
		rt = newnode();
	}
	inline void add(int x){
		rt = 1;
		for(int i=31; ~i; i--){
			id = x >> i & 1;
			if(!t[rt][id]) t[rt][id] = newnode();
			rt = t[rt][id];
			++cnt[rt];
		}
		end[rt] = 1, val[rt] = x;
	}
	inline int query(int x){
		rt = 1;
		for(int i=31; ~i; i--){
			id = x >> i & 1;
			if(t[rt][id^1]) rt = t[rt][id^1];
			else rt = t[rt][id];
		}
		return x ^ val[rt];
	}
} t; 

HDU 1251   统计难题

PS:统计前缀出现次数

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2000010;
int tot, tr[maxn][30], sum[maxn];

void insert(char *s, int rt){
	for(int i=0; s[i]; i++){
		int id = s[i]-'a';
		if(tr[rt][id]==0){
			tr[rt][id] = ++tot;
		}
		rt = tr[rt][id];
		sum[rt]++;
	}
}

int query(char *s, int rt){
	for(int i=0; s[i]; i++){
		int id = s[i]-'a';
		if(tr[rt][id]==0) return 0;
		rt = tr[rt][id];
	}
	return sum[rt];
}

int main(){
	char s[15];
	tot = 0;
	while(gets(s)){
		if(s[0]=='\0') break;
		insert(s, 0);
	}
	while(~scanf("%s", s)){
		printf("%d\n", query(s, 0));
	}
}

POJ 2001   Shortest Prefixes

PS:求最短、没有歧义的前缀

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2000010;
int tot, tr[maxn][30], sum[maxn];

void insert(char *s, int rt) {
	for(int i=0; s[i]; i++) {
		int id = s[i]-'a';
		if(tr[rt][id]==0) {
			tr[rt][id] = ++tot;
		}
		rt = tr[rt][id];
		sum[rt]++;
	}
}

void query(char *s, int rt) {
	string ans = "";
	for(int i=0; s[i]; i++) {
		int id = s[i]-'a';
		ans += s[i];
		rt = tr[rt][id];
		if(sum[rt]==1) {
			cout<<s<<" "<<ans<<endl;
			return;
		}
	}
	cout<<s<<" "<<s<<endl;
}

int main() {
	char s[1005][25];
	tot = 0;
	int cnt = 0;
	while(~scanf("%s", s[cnt])) {
		insert(s[cnt++], 0);
	}
	for(int i=0; i<cnt; i++) {
		query(s[i], 0);
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值