-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1097.cpp
More file actions
84 lines (74 loc) · 1.68 KB
/
Copy path1097.cpp
File metadata and controls
84 lines (74 loc) · 1.68 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
#include <iostream>
#include <vector>
using namespace std;
int N, K;
vector<string> vs;
vector<string> words;
vector<int> makeTable(string pattern) {
int patternSize = pattern.size();
vector<int> table(patternSize, 0);
int j = 0;
for(int i = 1; i < patternSize; i++) {
while(j > 0 && pattern[i] != pattern[j]) {
j = table[j - 1];
}
if(pattern[i] == pattern[j]) {
table[i] = ++j;
}
}
return table;
}
int KMP(string parent, string pattern) {
int ret = 0;
int parentSize = parent.size();
int patternSize = pattern.size();
vector<int> table = makeTable(pattern);
int j = 0;
for(int i = 0; i < parentSize -1; i++) {
while(j > 0 && parent[i] != pattern[j]) {
j = table[j - 1];
}
if(parent[i] == pattern[j]) {
if(j == patternSize - 1) {
ret++;
j = table[j];
}
else j++;
}
}
return ret;
}
void permutation(int depth) {
if(depth == N) {
string s;
for(int i = 0; i < N; i++) {
s.append(words[i]);
}
vs.push_back(s);
return;
}
for(int i = depth; i < N; i++) {
swap(words[depth], words[i]);
permutation(depth + 1);
swap(words[depth], words[i]);
}
}
int countMagic() {
int count = 0;
for(int i = 0; i < vs.size(); i++) {
if(KMP(vs[i]+vs[i],vs[i]) == K) count++;
}
return count*N;
}
int main() {
cin >> N;
for(int i = 0; i < N; i++) {
string s;
cin >> s;
words.push_back(s);
}
cin >> K;
permutation(1);
cout << countMagic();
return 0;
}