pat 1077 Kuchiguse(20 分) (字典树)

时间:2023-03-09 20:36:18
pat 1077 Kuchiguse(20 分) (字典树)
1077 Kuchiguse(20 分)

The Japanese language is notorious for its sentence ending particles. Personal preference of such particles can be considered as a reflection of the speaker's personality. Such a preference is called "Kuchiguse" and is often exaggerated artistically in Anime and Manga. For example, the artificial sentence ending particle "nyan~" is often used as a stereotype for characters with a cat-like personality:

  • Itai nyan~ (It hurts, nyan~)

  • Ninjin wa iyada nyan~ (I hate carrots, nyan~)

Now given a few lines spoken by the same character, can you find her Kuchiguse?

Input Specification:

Each input file contains one test case. For each case, the first line is an integer N (2≤N≤100). Following are N file lines of 0~256 (inclusive) characters in length, each representing a character's spoken line. The spoken lines are case sensitive.

Output Specification:

For each test case, print in one line the kuchiguse of the character, i.e., the longest common suffix of all N lines. If there is no such suffix, writenai.

Sample Input 1:

3
Itai nyan~
Ninjin wa iyadanyan~
uhhh nyan~

Sample Output 1:

nyan~

Sample Input 2:

3
Itai!
Ninjinnwaiyada T_T
T_T

Sample Output 2:

nai
 #include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <queue>
#include <set>
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
const int MAX = 1e5 + ; int n, rt = , str_len = INF;
struct node
{
int id, cnt, next[];
} P[MAX];
char shortest_str[];
stack <char> st; void init(int x)
{
for (int i = ; i <= ; ++ i)
P[x].next[i] = -;
} void my_insert(char *S, int len, int x)
{
int now = ;
for (int i = ; i < len; ++ i)
{
if (P[now].next[S[i]] == -)
{
P[now].next[S[i]] = ++ rt;
init(rt);
}
now = P[now].next[S[i]];
P[now].cnt ++;
}
} int my_find(int len)
{
int now = ;
for (int i = ; i < len; ++ i)
{
if (P[now].next[shortest_str[i]] == -) return -;
now = P[now].next[shortest_str[i]];
}
return P[now].cnt;
} int main()
{
// freopen("Date1.txt", "r", stdin);
scanf("%d", &n);
init();
getchar();
for (int i = ; i < n; ++ i)
{
char buf[];
string temp;
getline(cin, temp);
int len = temp.size();
for (int j = , k = len - ; k >= ; -- k, ++ j)
buf[j] = temp[k];
buf[len] = '\0';
my_insert(buf, len, i);
if (len < str_len)
{
str_len = len;
strcpy(shortest_str, buf);
}
} if (P[P[].next[shortest_str[]]].cnt != n)
{
printf("nai\n");
return ;
}
for (int i = str_len; i >= ; -- i)
{
if (my_find(i) == n)
{
for (int j = ; j < i; ++ j)
st.push(shortest_str[j]);
break;
}
}
while (st.size())
{
printf("%c", st.top());
st.pop();
} return ;
}