【kmp】F - Compress Words (codeforces)

题目:

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Input
The first line contains an integer nn (1≤n≤1051≤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 106106.

Output
In the only line output the compressed word after the merging process ends as described in the problem.

Examples
inputCopy
5
I want to order pizza
outputCopy
Iwantorderpizza
inputCopy
5
sample please ease in out
outputCopy
sampleaseinout
输入n个单词,按照顺序,求重叠最大并将重叠部分连接

思路:

kmp[ ]代表不包含当前位置字母,与模板串的最大数量的重叠子串。
通过kmp[ ]就可以找到最大重复子串的位置,从而使ch加上非重叠部分,最终求出字符串。

#include
#include
#include
#include
#include
#include
#include
using namespace std;
int n;
const int maxn=1000005;
int kmp[maxn];

int main()
{
    string ch;
    cin>>n;
    cin>>ch;
    int la=0,lb=0;
    for(int i=1;i>tmp;
        int j=0;
        lb=tmp.size();
        for(int i=2;i<=lb;i++)
        {
            while(j&&tmp[j]!=tmp[i-1])
            {
                j=kmp[j];
            }
            if(tmp[j]==tmp[i-1])
            {
                j++;
            }
            kmp[i]=j;
        }
        j=0;
        la=ch.size();
        for(int i=max(1,la-lb+1);i<=la;i++)    
        {
            while(j&&tmp[j]!=ch[i-1])
            {
                j=kmp[j];
            }
            if(tmp[j]==ch[i-1])
                j++;
        }
        for(int k=j;k

你可能感兴趣的:(题,kmp)