hihocoder1107(trie树)

题目链接

          http://hihocoder.com/problemset/problem/1107?sid=1355923


题意

          要求输入n个字符串,寻找有多少个最短合适子串。

          合适子串:最多有5个串以该串为前缀

          最短合适子串:s去掉最后一个字符后,就不是合适子串了。

          注意:""也要看作一个字符,也就是说ab,ac,ad,ae中的a并不满足条件。但是ab,ac,ad,ae,af,ag中的a就满足条件。


题解

         先全部读入进来,建立一棵trie树,用cnt数组标志每个节点被经过的次数。然后利用DFS,求出当前节点cnt值<=5,但它的父亲节点值>5的节点。对应最短合适子串的概念。

        一个注意点就是cnt[0]在一个子串进来的时候也要+1,因为""也是一个字符。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
using namespace std;

#define INIT(x) memset(x,0,sizeof(x))
#define eps 1e-8

typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1000005;

int trie[maxn][26],ans;
int cnt[maxn];

int k = 1;

void insert (char *w) {
	int len = strlen(w);
	int p = 0;
	cnt[0]++; //例如ab,ac,ad,ae,af,ag,由于a是记录在边上,而不是点上,所以要cnt[0]++ 
	for(int i=0;i<len;i++) {
		int c = w[i]-'a';
		if(!trie[p][c]) {
			trie[p][c] = k;
			k++;
		}
		p = trie[p][c];
		cnt[p]++;
 	}
}

void dfs(int x,int father) {
	if(x&&cnt[x]<=5&&cnt[father]>5) 
		ans++;
	else for(int i=0;i<26;i++) {
		if(trie[x][i]) {
			dfs(trie[x][i],x);
		}
	}
}

int n;
char s[maxn];

int main()
{
	while(cin>>n)
	{
		INIT(trie);
		INIT(cnt);
		ans = 0;
		k = 1;
		for(int i=0;i<n;i++) {
			scanf("%s",s);
			insert(s);
		}		
		dfs(0,-1);
		cout<<ans<<endl;
	}	
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

总想玩世不恭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值