HDU1711工程包:
C++源程序如下:
- #include <iostream>
- #include <cstdio>
- #include <vector>
- #include <cstring>
- #define MAX 1000100
- #define M 10010
- using namespace std;
- int a[MAX];
- int b[M];
- int NEXT[M];
- class Number_Sequence
- {
- int p,len1,len2;
- public:
- void initial();
- void read();
- void computing();
- void result();
- void getnext();
- void kmp();
- };
- void Number_Sequence::initial()
- {
- memset(a,0,sizeof(a));
- memset(b,0,sizeof(b));
- memset(NEXT,0,sizeof(NEXT));
- p=-1;
- }
- void Number_Sequence::read()
- {
- scanf("%d%d",&len1,&len2);
- for(int i=0;i<len1;i++)
- {
- scanf("%d",&a[i]);
- }
- for(int i=0;i<len2;i++)
- {
- scanf("%d",&b[i]);
- }
- }
- void Number_Sequence::getnext()
- {
- NEXT[0]=-1;
- int j=0,k=-1;
- while(j<len2)
- {
- if(k==-1||b[j]==b[k])
- {
- if(b[++j]==b[++k])
- {
- NEXT[j]=NEXT[k];
- }
- else
- NEXT[j]=k;
- }
- else
- k=NEXT[k];
- }
- }
- void Number_Sequence::kmp()
- {
- int i=0,j=0;
- while(i<len1&&j<len2)
- {
- if(j==-1||a[i]==b[j])
- {
- i++;
- j++;
- }
- else
- {
- j=NEXT[j];
- }
- if(j==len2)
- {
- p=i-j+1;
- break;
- }
- }
- if(j!=len2)
- {
- p=-1;
- }
- }
- void Number_Sequence::computing()
- {
- getnext();
- kmp();
- }
- void Number_Sequence::result()
- {
- cout<<p<<endl;
- }
- int main()
- {
- Number_Sequence ns;
- int cases;
- scanf("%d",&cases);
- for(int i=0;i<cases;i++)
- {
- ns.initial();
- ns.read();
- ns.computing();
- ns.result();
- }
- return 0;
- }
复制代码
所有资料51hei提供下载:
HDU 1711.rar
(241.11 KB, 下载次数: 5)
|