E. Compress Words(KMP模板题)

Problem - E - Codeforces

E. Compress Words(KMP模板题)_第1张图片

Examples

input

Copy

5
I want to order pizza

output

Copy

Iwantorderpizza

input

Copy

5
sample please ease in out

output

Copy

sampleaseinout

题解:

纯纯模板,本篇用来记录KMP最长字符串匹配模板

 

#include 
#include 
#include 
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
#define int long long
typedef pair PII; 
int ne[1000050];
string s,t;
int len;
void getnext()
{
	int i = 0;
	int j = - 1;
	ne[0] = -1;
	while(i < len)
	{
		if(j == -1||s[i] == s[j])
		{
			i++;
			j++;
			ne[i] = j;
		}
		else
		{
			j = ne[j];
		}
	}
}
int kmp(int st)
{
	int i = st,j = 0;
	int n = t.size();
	while(i < n)
	{
		while(j != -1&&t[i] != s[j])
		j = ne[j];
		i++;
		j++;
	}
	return j;
}
void solve()
{
	int n;
	cin >> n;
	cin >> t;
	for(int i = 1;i < n;i++)
	{
		cin >> s;
		len = s.size();
		getnext();
		int st = t.size() - len;
		st = max(0ll,st);
		int pos = kmp(st);
		t += s.substr(pos,len - pos + 1);
	}
	cout << t; 
}


signed main()
{
//	ios::sync_with_stdio(0);
//	cin.tie(0);cout.tie(0);
	int t = 1;
//	cin >> t;
	while(t--)
	{
		solve(); 
	}
}

你可能感兴趣的:(c++,图论,算法)