题目大意:对于每一个字符串,求一个它的前缀串,使这个前缀串能够唯一确定这个字符串。空串不能看做前缀。
还是更喜欢这种指针的写法。
code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#define IO \
ios::sync_with_stdio(false); \
// cin.tie(0); \
// cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
const int maxm = 16 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const double pi = acos(-1);
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, -1, -1, -1, 1, 1, 1, 1, -1};
char ch[1009][30];
typedef struct Node
{
int val;
Node *next[maxm];
} Trie;
string ans;
void insert(Trie *root, char *s)
{
int n = strlen(s);
Trie *p = root;
for (int i = 0; i < n; i++)
{
if (p->next[s[i] - 'a'] == NULL)
{
Trie *node = new Trie;
node->val = 0;
for (int j = 0; j < maxm; j++)
node->next[j] = NULL;
p->next[s[i] - 'a'] = node;
}
p = p->next[s[i] - 'a'];
p->val++;
}
return;
}
string query(Trie *root, char *s)
{
Trie *p = root;
int n = strlen(s);
for (int i = 0; i < n; i++)
{
p = p->next[s[i] - 'a'];
ans += s[i];
if (p->val == 1)
break;
}
return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
int i = 0;
while (cin >> ch[i])
i++;
int cnt = i;
Trie *root = new Trie;
root->val = 0;
for (int i = 0; i < maxm; i++)
root->next[i] = NULL;
for (int i = 0; i < cnt; i++)
{
char s[30];
strcpy(s, ch[i]);
insert(root, s);
}
for (int i = 0; i < cnt; i++)
{
char s[30];
strcpy(s, ch[i]);
ans = "";
cout << s << " " << query(root, s) << "\n";
}
return 0;
}