HDU 1711 Number Sequence 【KMP】

来源:互联网 发布:打水软件是什么 编辑:程序博客网 时间:2024/06/06 06:38

题目链接



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
213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
 

Sample Output
6-1


思路:简单KMP模版


WA: xt数组要初始化xt[1] = 1


AC代码:

#include <iostream>#include <stdio.h>#include <cstring>#define N 1000010#define M 10010using namespace std;int a[N],b[M],n,m,xt[M];void getnext(){    int j = 1;    xt[1]=1;//WA的地方!没有加这个初始化错了三次    for(int i = 2; i <= m; i++)    {        while(b[i] != b[j] && j > 1)            j = xt[j-1];        if(b[i] == b[j])            j++;        xt[i] = j;    }}int KMP(){    if(n < m)        return -1;    int j = 1;    for(int i = 1; i <= n; i++)    {        while(a[i] != b[j] && j > 1)            j = xt[j-1];        if(a[i] == b[j])            j++;        if(j == m+1)            return i-m+1;    }    return -1;}int main(){    int t;    scanf("%d", &t);    while(t--)    {        scanf("%d%d",&n, &m);        for(int i = 1; i <= n; i++)            scanf("%d", &a[i]);        for(int i = 1; i <= m; i++)            scanf("%d", &b[i]);        getnext();        printf("%d\n", KMP());    }}




 
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 发现被骗了报警不理怎么办 投稿投错了网站怎么办 六个月宝宝吃辅食便秘怎么办 六个月宝宝加辅食后便秘怎么办 婴儿6个月便秘怎么办 7个月的孩子便秘怎么办 四个月宝宝喜欢吃手怎么办 博瑞智教育是上当了怎么办 我43岁记忆力差怎么办 艾灸灸出的湿疹怎么办 饭店合同到期房东不租怎么办 极端暴力控制不住自己怎么办 苹果已停止访问该网页怎么办 qq登陆后隐藏了怎么办 易班密码忘记了怎么办 老师上课讲错了怎么办 专升本差了一分怎么办 登录不上学信网怎么办 steam被好友删了怎么办 护士继续教育学分证丢了怎么办 护士证到期未延续注册怎么办 学籍和户口不在一起小升初怎么办 定了酒店不能退怎么办 去哪儿网酒店不允许取消怎么办 快递寄送身份证扣海关怎么办 7岁龋齿烂到牙根怎么办 法院判完对方说没钱怎么办 初中填完志愿后怎么办 上海小学借读一年级没有学籍怎么办 学历不高的我该怎么办 没学历的我该怎么办 物业达不到服务标准该怎么办 没有能力的人该怎么办 工作累了腰疼怎么办 机场来早了6小时怎么办 苏宁金融综合评分不足怎么办 苏宁金融秒拒怎么办 微盘账号忘记了怎么办 天府e税忘记密码怎么办 未成年在外面没地方住怎么办? 半框眼镜片掉了怎么办