【kmp】F - Compress Words (codeforces)

2 篇文章 0 订阅
题目:

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<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<cstring>
#include<cmath>
#include<algorithm>
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<n;i++)
    {
        string tmp;
        //cout<<tmp<<endl;
        cin>>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<lb;k++)
        {
            ch+=tmp[k];
        }
    }
    cout<<ch<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值