复制Markdown 展开
题目描述
Amugae has a sentence consisting of nn words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".
Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.
输入格式
The first line contains an integer nn ( 1 \le n \le 10^51≤n≤105 ), the number of the words in Amugae's sentence.
The second line contains nn words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed 10^6106 .
输出格式
In the only line output the compressed word after the merging process ends as described in the problem.
题意翻译
Amugae有n个单词,他想把这个n个单词变成一个句子,具体来说就是从左到右依次把两个单词合并成一个单词.合并两个单词的时候,要找到最大的i(i\ge 0)i(i≥0),满足第一个单词的长度为ii的后缀和第二个单词长度为ii的前缀相等,然后把第二个单词第ii位以后的部分接到第一个单词后面.输出最后那个单词
输入输出样例
输入 #1复制
5 I want to order pizza输出 #1复制
Iwantorderpizza输入 #2复制
5 sample please ease in out输出 #2复制
sampleaseinout
1.这一道题标签是kmp算法。
2.这道题我使用了很多种方法,先是暴力然后没过。后面就发现这道题的意思是我们合并前俩个字符串,但是第三个字符串合并的时候是和前面的结果字符串合并,而不是相邻的字符串合并。
3.后面我就一直优化总结的算法,后面终于没有出错了但是他给我了一个UKE,未知的错误。
4.然后就是看别人写的题解我发现他们使用到了kmp算法,使用后面的字符串作为模式串。
5,然后我就优化了kmp,因为我觉得单纯kmp还是没有那么好,时间复杂度还是很高。但是很遗憾的是提交上去还是UKE。
C代码如下 :
#include<stdio.h>
#include<string.h>
char s[50],res[1000010];
int m;
char next(char s[],int nxt[])
{
int i,j;
for(i=1,j=0;s[i];)
{
while(s[i]==s[j]&&s[i])
{
j++;
nxt[i]=j;
i++;
}
j=nxt[j-1];
while(s[i]!=s[j]&&s[i]&&j==0)
{
nxt[i]=0;
i++;
}
}
// for(j=0;s[j];j++) printf("%d ",nxt[j]);
}
char kmp(char s[])
{
int i,j=0,nxt[50]={0},n=strlen(s);
next(s,nxt);
for(i=(m>n?m-n:0);res[i];)
{
while(res[i]==s[j]&&res[i])
{
i++;
j++;
}
if(res[i]==0)
{
break;
}
j=nxt[j];
while(res[i]!=s[j]&&res[i]&&j==0) i++;
}
while(s[j])
{
res[i++]=s[j++];
m++;
}
}
int main()
{
int n,i;
scanf("%d",&n);
scanf("%s",res);
m=strlen(res);
for(i=1;i<n;i++)
{
scanf("%s",s);
kmp(s);
}
printf("%s",res);
}
C++代码如下:
#include<iostream>
#include<bits/stdc++.h>
#include<cstring>
using namespace std;
char s[50],res[1000010];
int m;
char next(char s[],int nxt[])
{
int i,j;
for(i=1,j=0;s[i];)
{
while(s[i]==s[j]&&s[i])
{
j++;
nxt[i]=j;
i++;
}
j=nxt[j-1];
while(s[i]!=s[j]&&s[i]&&j==0)
{
nxt[i]=0;
i++;
}
}
// for(j=0;s[j];j++) printf("%d ",nxt[j]);
}
char kmp(char s[])
{
int i,j=0,nxt[50]={0},n=strlen(s);
next(s,nxt);
for(i=(m>n?m-n:0);res[i];)
{
while(res[i]==s[j]&&res[i])
{
i++;
j++;
}
if(res[i]==0)
{
break;
}
j=nxt[j];
while(res[i]!=s[j]&&res[i]&&j==0) i++;
}
while(s[j])
{
res[i++]=s[j++];
m++;
}
}
int main()
{
int n,i;
cin >> n;
cin >> res;
m=strlen(res);
for(i=1;i<n;i++)
{
cin >> s;
kmp(s);
}
cout << res << endl;
}