<소스 코드>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test;
cin >> test;
vector<int> kmp_table;
for (int t = 1; t <= test; t++)
{
string book;
string pattern;
cin >> book >> pattern;
kmp_table.clear();
kmp_table.resize(pattern.length() + 1);
fill(kmp_table.begin(), kmp_table.end(), 0);
// 문자열이 NULL이 아닐 때까지
for (int i = 1; pattern[i]; i++)
{
int j = kmp_table[i - 1];
while (j > 0 && pattern[i] != pattern[j])
j = kmp_table[j - 1];
if (pattern[i] == pattern[j])
kmp_table[i] = ++j;
}
int ans = 0;
int j = 0;
for (int i = 0; book[i]; i++)
{
while (j > 0 && book[i] != pattern[j])
j = kmp_table[j - 1];
if (book[i] == pattern[j])
{
if (j == (pattern.length() - 1))
{
ans++;
j = kmp_table[j];
}
else
j++;
}
}
cout << '#' << t << ' ' << ans << '\n';
}
return 0;
}
|
cs |