Shortest Prefixes POJ - 2001 (字典树)

Shortest Prefixes - POJ 2001 - Virtual Judge (csgrandeur.cn)

一道字典树的题,题意是给出很多字符串,求出每个可以唯一代表此字符串的最短前缀。

唯一代表的最短前缀的条件的是没有其他的字符串和其有相同的前缀。

可以用字典树储存每一层的字符的个数,当个数为1时说明之后的字符串唯一,之前的前缀便可作为唯一最短前缀。

代码如下:

#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cstdio>
#define INF 0x3f3f3f3f
#define ll long long
#define ull unsigned long long
#define inf 0x3f3f3f3f3f3f3f3f
#define mem(a, b) memset(a, b, sizeof(a))
#define rep(i, a, b) for (auto i = a; i <= b; ++i)
#define bep(i, a, b) for (auto i = a; i >= b; --i)
#define lowbit(x) x &(-x)
#define PII pair<int, int>
#define PLL pair<ll, ll>
#define PI acos(-1)
#define pb push_back
#define eps 1e-6
#define X1 first
#define Y1 second
#define IOS                      \
    ios::sync_with_stdio(false); \
    cin.tie(0);                  \
    cout.tie(0);
const int MO = 1e9 + 10;
const int NN = 1e8 + 10;
const int MM = 1e7 + 10;
const int N = 1e6 + 10;
const int M = 2e5 + 10;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int dxy[][2] = {{0, 1}, {1, 0}, {1, 1}, {-1, 1}};
using namespace std;

char str[30000][26];//数据范围要开大,至少是字符串条数*26
int son[30000][26],idx;
int now[30000];
void insert(char st[])
{
	int p=0;
	for(int i=0;st[i];i++)
	{
		int u=st[i]-'a';
		if(!son[p][u])
		son[p][u]=++idx;
		p=son[p][u];
		now[p]++;//每存一次便要++
	}
}
string search(char st[])
{
	int p=0;
	string a="";
	for(int i=0;st[i];i++)
	{
		int u=st[i]-'a';
		p=son[p][u];
		a+=st[i];
		if(now[p]==1)
		return a;
	}
	return a;
}
int main()
{
	
	int cnt=0;
	while(cin>>str[++cnt])
	{
		insert(str[cnt]);
	}
	for(int i=1;i<=cnt;i++)
	{
		cout<<str[i]<<" "<<search(str[i])<<endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值