-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp_parallel.cpp
More file actions
86 lines (68 loc) · 1.59 KB
/
kmp_parallel.cpp
File metadata and controls
86 lines (68 loc) · 1.59 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
#include<bits/stdc++.h>
#include<omp.h>
#define NUM_THREADS 4
using namespace std;
int* kmp_init(string v, int m) {
int *f = new int[m+1];
f[0]=0; f[1]=0;
int i=2, j=0;
while (i<=m) {
if (v[j]==v[i-1]) {
j++;
f[i]=j;
i++;
}
else if (j==0) {
f[i]=0;
i++;
}
else {
j=f[j];
}
}
return f;
}
void kmp_search(string v, string b, char r[], int m, int n, int* f) {
int i=0, j=0;
while (i<n) {
if (v[j]==b[i]) {
j++;
i++;
if (j==m) {
j=f[j];
r[i-m]=1;
}
} else if (j==0) {
i++;
}
else {
j=f[j];
}
}
}
void kmp_parallel(int p, string v, string b, char r[], int m, int n) {
omp_set_num_threads(p);
int *f = kmp_init(v,m);
int pos=n-m+1;
#pragma omp parallel for
for (int proc=0;proc<p;proc++) {
int start=proc*pos/p;
int end=(proc+1)*pos/p;
kmp_search(v,b.substr(start, end-start+m),r+start,m,end-start+m-1,f);
}
}
int main() {
ifstream fin;
string a, t;
fin.open("2.txt");
getline(fin, t);
fin.close();
cin>>a;
int n = t.size(), m = a.size();
char *r = new char[n];
clock_t ct = clock();
kmp_parallel(NUM_THREADS,a,t,r,m,n);
ct = clock() - ct;
cout << (double)(((double)ct)/CLOCKS_PER_SEC) << endl;
return 0;
}