8.11 I

来源:互联网 发布:淘宝手机直通车怎么找 编辑:程序博客网 时间:2024/05/29 18:51

                                   I - Number Sequence


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, outputthe smallest one. 


Input

The first line of input is a number T which indicate thenumber of cases. Each case contains three lines. The first line is two numbersN and M (1 <= M <= 10000, 1 <= N <= 1000000). The second linecontains N integers which indicate a[1], a[2], ...... , a[N]. The third linecontains M integers which indicate b[1], b[2], ...... , b[M]. All integers arein the range of [-1000000, 1000000]. 


Output

For each test case, you should output one line which onlycontain 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

 

题意:输入一个数字t,有t组数据,对于每一组数据输入两个数字m,n,然后输入两个长度为m,n的字符串,判断第二个字符串是否在第一个字符串中出现过,如果出现过,输出起始点下标,如果没有出现,输出-1。

思路:用next数组比较,对于每一次比较的情况存入extend数组,然后判断extend数组中是否含有与第二个字符串相等的数字,如果有,则将该点下标减去第二个字符串长度输出。也可以直接在next数组中比较。

 

#include<stdio.h>#include<string.h>int s1[1110000],s2[1110000],next[1110000],extend[1110000];int main(){int i,j,k,T,m,n,max,f;while(scanf("%d",&T)!=EOF){while(T--){scanf("%d%d",&m,&n);memset(next,0,sizeof(next));memset(extend,0,sizeof(extend));for(i=0;i<m;i++){scanf("%d",&s1[i]);}for(j=0;j<n;j++){scanf("%d",&s2[j]);}j=0;for(i=1;i<n;)//计算next数组{if(s2[i]==s2[j]){next[i]=j+1;i++;j++;}else if(j==0&&s2[i]!=s2[j]){i++;}else if(j>0&&s2[i]!=s2[j]){j=next[j-1];}}/*for(i=0;i<n;i++){printf("%d ",next[i]);}printf("\n");*/i=0;j=0;while(i<m&&j<n){if(s1[i]==s2[j]){extend[i]=j+1;i++;j++;}else if(j==0&&s1[i]!=s2[j]){extend[i]=j;i++;}else if(i>0&&s1[i]!=s2[j]){j=next[j-1];extend[i]=0;}}/*for(i=0;i<m;i++){printf("%d ",extend[i]);}printf("\n");*/max=0;for(i=0;i<m;i++){if(extend[i]==n){f=i;//记录位置max=1;//记录是否完全重合break;}}if(max==1){printf("%d\n",f-n+2);//因为字符串是从0开始输出的是重合时的第一位所以加上2}else{printf("-1\n");}}}return 0;}


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 做人事招不到人怎么办 苹果6cpu坏了怎么办 苹果6s升级不了怎么办 冬天打游戏手冷怎么办 漂流瓶不能用了怎么办 感冒鼻子闻不到味道怎么办 胃难受想吐头晕怎么办 心口窝堵得慌怎么办 嘴巴里苦的很怎么办 怀孕了嘴巴好苦怎么办 嘴巴没味道想吐怎么办 手机流量不够用怎么办移动 sd卡图片不显示怎么办 苹果忘了id账号怎么办 苹果id号忘记了怎么办 7icloud存储满了怎么办 苹果6icloud满了怎么办 电脑内存槽坏了怎么办 苹果7照片删不了怎么办 屋里太冷怎么办小妙招 天气太热,没空调怎么办 8岁儿童发烧39度怎么办 4岁儿童发烧39度怎么办 6岁儿童发烧39度怎么办 手机被晒得很烫怎么办 子宫肌瘤引起的贫血怎么办 月子没做好腰疼怎么办 狗狗屁股流血水怎么办 狗狗屁股在流血怎么办 劳累引起的腰疼怎么办 心口发闷堵的慌怎么办 刨腹产后肚子大怎么办 c盘空间不够用怎么办 敷面膜玩手机了怎么办 领导想辞退我该怎么办 领导要辞退我要怎么办 想辞职老板不批怎么办 辞职后工资不给怎么办 闻组词表示听见怎么办 染完头发后悔了怎么办 跟不好的人相处怎么办