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;
}