資料結構實驗之串三:KMP應用 sdut(oj 3311)
阿新 • • 發佈:2019-01-29
資料結構實驗之串三:KMP應用
Time Limit: 1000ms Memory limit: 65536K 有疑問?點這裡^_^
題目描述
有n個小朋友,每個小朋友手裡有一些糖塊,現在這些小朋友排成一排,編號是由1到n。現在給出m個數,能不能唯一的確定一對值l和r(l <= r),使得這m個數剛好是第l個小朋友到第r個小朋友手裡的糖塊數?輸入
首先輸入一個整數n,代表有n個小朋友。(0輸出
如果能唯一的確定一對l,r的值,那麼輸出這兩個值,否則輸出-1示例輸入
5 1 2 3 4 5 3 2 3 4
示例輸出
2 4
提示
來源
windream
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> using namespace std; int n, m; int next[1000100]; int s[1000010], t[1000010]; void get_next(int t[], int next[]) { int i=1; next[1] = 0; int j = 0; while(i < m) { if(j == 0 || t[i] == t[j]) { ++i; ++j; next[i] = j; } else j = next[j]; } } void KMP(int n, int m) { int pos=1; int k = 1; int f=0, h; while(pos <= n&&k <= m) { if(k == 0 || s[pos] == t[k]) { ++pos; ++k; } else { k = next[k]; } if(k > m) { k = 1; f++; if(f == 1) { // d = 1; h = pos; } } } if(f == 1) printf("%d %d\n", h-m, h-1); else printf("-1\n"); } int main() { int n, m; scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", &s[i]); scanf("%d", &m); for(int j = 1; j <= m; j++) scanf("%d", &t[j]); get_next(t, next); KMP(n, m); return 0; }