-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp.cpp
128 lines (113 loc) · 2.53 KB
/
kmp.cpp
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include<iostream>
#include<vector>
#include<string.h>
#include<algorithm>
#include<queue>
#include<sys/time.h>
#include<unistd.h>
#include <sys/resource.h>
#define ll long long
using namespace std;
const int N = 2010000;
const int dataN = 1e6; // 随机串s的长度
char s[N];
char p[N];
double usedTime;
ll usedMem;
struct Node {
int start = 0;
int end = 0;
Node(): start(0), end(0) {}
Node(int a, int b): start(a), end(b) {}
};
struct MatchResult {
ll matchStringNum = 0;
char *pattern = NULL;
vector<Node*> posList;
}matchRes;
ll maxll(ll a, ll b) {
if (a > b)
return a;
return b;
}
void calculateTime(timeval& tStart, timeval& tFinish) {
// 转ms
usedTime = (tFinish.tv_sec-tStart.tv_sec)*1000000 + (tFinish.tv_usec-tStart.tv_usec);
printf("执行耗时: %.10lfms\n", usedTime);
}
ll getMemoryUsage() {
struct rusage usage;
if(0 == getrusage(RUSAGE_SELF, &usage))
return usage.ru_maxrss; // bytes
else
return 0;
}
void calculateMem() {
printf("内存占用: %.2lfMB\n", (double)usedMem/(1024*1024));
}
void outputMatchRes() {
printf("匹配串: %s 匹配数量: %lld\n", matchRes.pattern, matchRes.matchStringNum);
int posListSize = matchRes.posList.size();
if (posListSize == 0) {
printf("无匹配串\n");
return;
}
printf("匹配坐标:\n");
for(int i = 0; i<posListSize; i++) {
printf("启始:%d 终止:%d\n", matchRes.posList[i]->start, matchRes.posList[i]->end);
}
}
void KMP(char s[], char p[], ll lens, ll lenp) {
int next[N];
ll i=0, j=-1;
next[i] = j;
while(i < (lenp-1)) {
if (j==-1 || p[i]==p[j]) {
i++, j++;
if(p[i] != p[j])
next[i] = next[j];
else
next[i] = j;
}else
j = next[j];
}
usedMem = maxll(usedMem, getMemoryUsage());
i=0, j=0;
while (i<lens) {
if(j==-1 || s[i]==p[j])
i++, j++;
else
j = next[j];
if(j==lenp) {
Node* tmp = new Node(i-j, i-j+lenp);
matchRes.posList.push_back(tmp);
matchRes.matchStringNum++;
//模拟vscode cmd+f, 不存在重叠
j = 0;
}
}
usedMem = maxll(usedMem, getMemoryUsage());
}
void randomData(char a[]) {
srand((int)time(0));
for(int i = 0; i<dataN; i++) {
a[i] = char(rand()%26 + 'a');
}
}
int main() {
randomData(s);
timeval tStart, tFinish;
while(scanf("%s", p)) {
matchRes.matchStringNum = 0;
matchRes.posList = vector<Node*>();
ll lens = strlen(s), lenp = strlen(p);
gettimeofday(&tStart, NULL);
KMP(s, p, lens, lenp);
gettimeofday(&tFinish, NULL);
outputMatchRes();
calculateTime(tStart, tFinish);
usedMem = maxll(usedMem, getMemoryUsage());
calculateMem();
}
return 0;
}