求助,11,13两个点TLE了
查看原帖
求助,11,13两个点TLE了
108101
Katomegumi楼主2022/4/1 21:10
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char pat[1000005], txt[1000005];
int now=0,k,temp;
int* buildnext(char* pat)//自己和自己匹配,记录前i个字符中最长相等前后缀的长度
{
	//pat此时作为文本串与自身进行匹配
	int m = strlen(pat), j = 0;
	int* N = new int[m+1];//构建next数组
	int t = -1;
	N[0] = -1;//表示说如果第一位就不匹配 那么进入下面的match函数j<0中,直接使得模式串右移一位
	while (j < m )
	{
		if (t < 0 || pat[j] == pat[t])
		{
			++t, ++j;
			N[j] = t;
		}
		else//失配
			t = N[t];
	}
	return N;
}

void match(char* pat, char* txt)
{
	//对于给出的pat,构建一个next数组
	int* next = buildnext(pat);
	int m = strlen(pat), j = 0;
	int n = strlen(txt);
	while (j < m && now < n)
	{
		if (j < 0 || pat[j] == txt[now])
			++now, ++j;
		else
			j = next[j];
	}
	delete[] next;//释放next数组
	if (now - j <= n - m && now - j + 1 != temp)
	{
		cout << now - j + 1 << endl;
		temp = now - j + 1;
		now = now - j + 2;
		match(pat, txt);
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> txt >> pat;
	match(pat, txt);
	int *s2 = buildnext(pat);
	int m = strlen(pat);
	for (int i = 1; i <= m; ++i)
		cout << s2[i] << " ";
}
2022/4/1 21:10
加载中...