您的位置:首页 > 其它

HDU_1711解题报告

2016-08-12 15:28 211 查看
非常好的一篇KMP算法入门:

http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

唉,不知道为什么还是WA。。

import java.util.*;
public class Main {
static int n,m;
static int[] a = new int[1000000];
static int[] b = new int[10000];
static int[] next = new int[10000];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0;i<t;i++){
n = sc.nextInt();
m = sc.nextInt();
for(int j=0;j<n;j++){
a[j]=sc.nextInt();
}
for(int j=0;j<m;j++){
b[j]=sc.nextInt();
}
int[] next = new int[m];
if(n<m) System.out.println("-1");
else{
getnext();
System.out.println(kmp());
}
}
}
public static void getnext(){
next[0]=0;
int k=0;
for(int i=1;i<m;i++){
while(k>0&&b[k]!=b[i])
k=next[k-1];
if(b[k]==b[i]) k++;
next[i]=k;
}
}
public static int kmp(){
for(int i=0;i<n;i++){
int x=0;
for(int j=0;j<m;j++){
if(b[j]==a[i+x]){
x++;
}else{
break;
}

}
if(x==m){return i+1;}
else{
i+=(x-next[x]);
}
}
return -1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: