1. 程式人生 > 實用技巧 >剪花布條(KMP)HDU-2087

剪花布條(KMP)HDU-2087

一塊花布條,裡面有些圖案,另有一塊直接可用的小飾條,裡面也有一些圖案。對於給定的花布條和小飾條,計算一下能從花布條中儘可能剪出幾塊小飾條來呢?


入門題:直接套模板就好,不會KMP的同學上網隨便找一篇大佬的部落格就可以了(自己寫起來太麻煩了


#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<algorithm>
#include<map>
#include<queue>
#include
<set> #include <sstream> #include<vector> #include<cmath> #include<stack> #include<time.h> #include<ctime> using namespace std; #define inf 1<<30 #define eps 1e-7 #define LD long double #define LL long long #define maxn 1000005 int Next[maxn] = {}; void
GetNext(string s)//找到Next陣列 { memset(Next, 0, sizeof(Next)); int i = 0; int j = -1; int len = s.length(); Next[0] = -1; while (i < len) { if (j == -1 || s[i] == s[j]) { i++; j++; Next[i] = j; } else { j
= Next[j]; } } } int Kmp(string p, string s) { GetNext(s); int i = 0; int j = 0; int len1 = p.length(); int len2 = s.length(); int sum = 0; while (i < len1) { if (j == -1 || p[i] == s[j]) { i++; j++; } else { j = Next[j]; } if (j == len2)//找到一個 { sum++;//加一 j =0;//j清零 } } return sum; } int main() { string p, s; while (cin >> p) { if (p == "#")break; cin >> s; printf("%d\n", Kmp(p, s)); } }