HDU 1711 Number Sequence(KMP裸题,板子题,有坑点)

时间:2023-03-08 17:12:03
HDU 1711 Number Sequence(KMP裸题,板子题,有坑点)

Number Sequence

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 27028    Accepted Submission(s): 11408

Problem Description
Given
two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2],
...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your
task is to find a number K which make a[K] = b[1], a[K + 1] = b[2],
...... , a[K + M - 1] = b[M]. If there are more than one K exist, output
the smallest one.
Input
The
first line of input is a number T which indicate the number of cases.
Each case contains three lines. The first line is two numbers N and M (1
<= M <= 10000, 1 <= N <= 1000000). The second line contains
N integers which indicate a[1], a[2], ...... , a[N]. The third line
contains M integers which indicate b[1], b[2], ...... , b[M]. All
integers are in the range of [-1000000, 1000000].
Output
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
Sample Input
2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1
Sample Output
6
-1
Source
分析:KMP裸题,自己看吧,不会的看我博客详解!此题有道坑点就是读入不能用cin读入,很容易T!
HDU 1711 Number Sequence(KMP裸题,板子题,有坑点)

HDU 1711 Number Sequence(KMP裸题,板子题,有坑点)

纯粹要看运气才会过QAQ

优化以后:

HDU 1711 Number Sequence(KMP裸题,板子题,有坑点)

速度快了将近3.5s,scanf大法好啊

下面给出AC代码:
 #include <bits/stdc++.h>
using namespace std;
const int N=;
inline int read()
{
int x=,f=;
char ch=getchar();
while(ch<''||ch>'')
{
if(ch=='-')
f=-;
ch=getchar();
}
while(ch>=''&&ch<='')
{
x=x*+ch-'';
ch=getchar();
}
return x*f;
}
int kmpnext[N];
int s[N],t[N];///s为主串,t为模式串
int slen,tlen;///slen为主串的长度,tlen为模式串的长度
inline void getnext()
{
int i,j;
j=kmpnext[]=-;
i=;
while(i<tlen)
{
if(j==-||t[i]==t[j])
{
kmpnext[++i]=++j;
}
else
{
j=kmpnext[j];
}
}
}
/*
返回模式串T在主串S中首次出现的位置
返回的位置是从0开始的。
*/
inline int kmp_index()
{
int i=,j=;
getnext();
while(i<slen&&j<tlen)
{
if(j==-||s[i]==t[j])
{
i++;
j++;
}
else
j=kmpnext[j];
}
if(j==tlen)
return i-tlen;
else
return -;
}
/*
返回模式串在主串S中出现的次数
*/
inline int kmp_count()
{
int ans=;
int i,j=;
if(slen==&&tlen==)
{
if(s[]==t[])
return ;
else
return ;
}
getnext();
for(i=;i<slen;i++)
{
while(j>&&s[i]!=t[j])
j=kmpnext[j];
if(s[i]==t[j])
j++;
if(j==tlen)
{
ans++;
j=kmpnext[j];
}
}
return ans;
}
int T;
int main()
{
T=read();
while(T--)
{
slen=read();
tlen=read();
for(int i=;i<slen;i++)
s[i]=read();
for(int i=;i<tlen;i++)
t[i]=read();
if(kmp_index()==-)
cout<<-<<endl;
else
cout<<kmp_index()+<<endl;
}
return ;
}