8.11 I - Number Sequence

                                   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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值