-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1786.cpp
More file actions
87 lines (67 loc) ยท 2.54 KB
/
1786.cpp
File metadata and controls
87 lines (67 loc) ยท 2.54 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string T, P;
//N์์ ์๊ธฐ ์์ ์ ์ฐพ์ผ๋ฉด์ ๋ํ๋๋ ๋ถ๋ถ ์ผ์น๋ฅผ ์ด์ฉํด pi[] ๊ณ์ฐ
//pi[i] = N[..i]์ ์ ๋ฏธ์ฌ๋ ๋๊ณ ์ ๋์ฌ๋ ๋๋ ๋ฌธ์์ด์ ์ต๋ ๊ธธ์ด
vector<int> getPartialMatch(const string &N){
int M = N.size();
vector<int> pi(M, 0);
//KMP๋ก ์๊ธฐ ์์ ์ ์ฐพ๋๋ค
//N์ N์์ ์ฐพ๋๋ค.
//begin=0์ด๋ฉด ์๊ธฐ ์์ ์ ์ฐพ์๋ฒ๋ฆฌ๋๊น ์๋จ!
int begin = 1, matched = 0;
//๋น๊ตํ ๋ฌธ์๊ฐ N์ ๋์ ๋๋ฌํ ๋๊น์ง ์ฐพ์ผ๋ฉด์ ๋ถ๋ถ ์ผ์น๋ฅผ ๋ชจ๋ ๊ธฐ๋กํ๋ค
while (begin + matched < M){
if (N[begin + matched] == N[matched]){
matched++;
pi[begin + matched - 1] = matched;
}
else{
if (matched == 0)
begin++;
else{
begin += matched - pi[matched - 1];
matched = pi[matched - 1];
}
}
}
return pi;
}
vector<int> kmpSearch2(const string &H, const string &N){
int n = H.size(), m = N.size();
vector<int> result;
vector<int> pi = getPartialMatch(N);
//ํ์ฌ ๋์๋ ๊ธ์์ ์
int matched = 0;
//์ง๋๋ฏธ์ ๊ฐ ๊ธ์๋ฅผ ์ํ
for (int i = 0; i < n; i++){
//matched๋ฒ ๊ธ์์ ์ง๋๋ฏธ์ ํด๋น ๊ธ์๊ฐ ๋ถ์ผ์นํ ๊ฒฝ์ฐ,
//ํ์ฌ ๋์๋ ๊ธ์์ ์๋ฅผ pi[matched-1]๋ก ์ค์ธ๋ค
while (matched > 0 && H[i] != N[matched])
matched = pi[matched - 1];
//๊ธ์๊ฐ ๋์๋ ๊ฒฝ์ฐ
if (H[i] == N[matched]){
matched++;
if (matched == m){
//๋ฌธ์ ์์ ์ธ๋ฑ์ค๋ 0์ด ์๋ 1๋ถํฐ ์์
result.push_back(i - m + 2);
matched = pi[matched - 1];
}
}
}
return result;
}
int main(void){
ios_base::sync_with_stdio(0);
cin.tie(0); //cin ์๋ ํฅ์ ์ํด
getline(cin, T); //๊ณต๋ฐฑ ํฌํจํด์ ์
๋ ฅ๋ฐ๊ธฐ ์ํด
getline(cin, P);
vector<int> result = kmpSearch2(T, P);
//endl ์ฐ๋ฉด ์๊ฐ ์ด๊ณผ
cout << result.size() << "\n";
for (int i = 0; i < result.size(); i++)
cout << result[i] << "\n";
return 0;
}