-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP_Algorithm.cpp
More file actions
165 lines (144 loc) · 2.86 KB
/
KMP_Algorithm.cpp
File metadata and controls
165 lines (144 loc) · 2.86 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
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
//
// main.cpp
// Proj2_3530
//
// Created by Zain Lateef on 12/1/16.
// Copyright © 2016 Zain Lateef. All rights reserved.
//
#include<iostream>
#include<string>
int kmp(std::string target,std::string source)
{
int targ_len=target.length();
int orange=0,i=1,j=0,cnt=0;
int holder[targ_len];
holder[0]=0;
while(i<targ_len)
{
if(target[i]==target[cnt])
{
cnt++;
holder[i]=cnt;
i++;
}
else
{
if(cnt!=0)
{
cnt=holder[cnt-1];
}
else
{
holder[i]=0;
i++;
}
}
}
int text_len=source.length();
i=0;
while(i<text_len)
{
if(target[j]==source[i])
{
i++;
j++;
}
if(j==targ_len)
{
orange++;
j=holder[j-1];
}
else if(target[j]!=source[i]&&i<text_len)
{
if(j!=0)
j=holder[j-1];
else
i=i+1;
}
}
return orange;
}
void longest(int *rows,int *cols,int en)
{
int uno_mas=en+1,i,j;
int holder[uno_mas][uno_mas];
for(i=0;i<uno_mas;i++)
{
for(j=0;j<uno_mas;j++)
{
if(i==0||j==0)
holder[i][j]=0;
else if(rows[i-1]==cols[j-1])
holder[i][j]=holder[i-1][j-1]+1;
else
{
if(holder[i-1][j]>holder[i][j-1])
holder[i][j]=holder[i-1][j];
else
holder[i][j]=holder[i][j-1];
}
}
}
/*Print
for(i=0;i<en;i++)
std::cout<<holder[i];
std::cout<<std::endl;
*///
int k=holder[en][en];
int size=k+1;
int tantra[size];
i=en,j=en;
while(i>0&&j>0)
{
if(rows[i-1]==cols[j-1])
{
tantra[k-1]=rows[i-1];
i--;
j--;
k--;
}
else if (holder[i-1][j]>holder[i][j-1])
i--;
else
j--;
}
for(i=0;i<size-1;i++)
std::cout<<tantra[i]<<" ";
}
int main()
{
std::string hint, input;
int en,i,j,k,l;
std::cin>>hint;
std::cin>>en;
int rows[en],cols[en];
char colera[en*en];
for(i=0;i<en;i++)
{
std::cin>>input;
rows[i]=kmp(hint,input);
k=i;
for(j=0;j<en;j++)
{
colera[k]=input[j];
k=k+en;
}
}//2n^2
std::string strung(colera);
l=0;
for(i=0;i<en;i++)
{
cols[i]=kmp(hint,strung.substr(l,en));
l=l+en;
}//2n^2+n^2=3n^2
/*Print
for(i=0;i<en;i++)
std::cout<<rows[i];
std::cout<<std::endl;
for(i=0;i<en;i++)
std::cout<<cols[i];
std::cout<<std::endl;
*///Combination found
longest(rows,cols,en);
return 0;
}