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。。
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; } }
相关文章推荐
- hdu 1711 Number Sequence 解题报告
- Hdu 1084 What Is Your Grade?解题报告
- HDU--2104--hide handkerchief--解题报告(辗转相除的运用)
- hdu 1064 解题报告
- HDU 2680 Choose the best route 解题报告
- HDU 3732 Ahui Writes Word 解题报告
- hdu 1102 pku 2421 解题报告
- HDU 1870 愚人节的礼物 解题报告
- HDU 2469 Fire-control System解题报告
- hdu 2139解题报告
- HDU 1231 畅通工程 解题报告
- HDU第11版解题报告(农夫版)
- hdu 2516解题报告
- HDU 3335 解题报告
- hdu 1019解题报告
- Hdu 1009 FatMouse' Trade解题报告
- HDU 3336 解题报告
- 终曲(hdu 2572)解题报告
- HDU 1158 Emloyment Planning 解题报告
- HDU 1856 More is better 解题报告