1.KMP字符串匹配
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int main() {
int ne[N];
string s, st;
cin >> s >> st;
//next
int c = 0, d = -1;
ne[0] = -1;
while (c < st.size()) {
if (d == -1 || st[c] == st[d]) {
ne[++c] = ++d;
} else
d = ne[d];
}
//kmp
c = 0, d = 0;
while (c < s.size()) {
if (d == -1 || s[c] == st[d]) {
c++;
d++;
} else
d = ne[d];
if (d == st.size())
cout << c - d + 1 << endl;
}
//cout
for (int i = 0; i < st.size(); i++) {
if (i)
cout << " ";
cout << ne[i + 1] ;
}
}
2.串的模式匹配
#include <bits/stdc++.h>
using namespace std;
const int M = 1e5 + 1000;
const int N = 35;
int ne[M];
int main() {
string s, st;
int n, m;
cin >> s >> n;
while (n--) {
cin >> st;
//next
int c = 0, d = -1;
ne[0] = -1;
while (c < st.size()) {
if (d == -1 || st[c] == st[d]) {
ne[++c] = ++d;
} else
d = ne[d];
}
//kmp
int flag = 0;
c = 0, d = 0;
while (c < s.size()) {
if (d == -1 || s[c] == st[d]) {
c++;
d++;
} else
d = ne[d];
if (d == st.size()) {
flag = 1;
break;
}
}
//cout
if (flag == 1) {
for (int i = c - d; i < s.size(); i++)
cout << s[i];
cout << "\n";
} else {
cout << "Not Found" << endl;
}
}
}
3.字符串模式匹配
#include <bits/stdc++.h>
using namespace std;
const int M = 1e5 + 1000;
const int N = 35;
int ne[M];
int main() {
string s, st;
int n, m;
cin >> s >> st;
//next
int c = 0, d = -1;
ne[0] = -1;
while (c < st.size()) {
if (d == -1 || st[c] == st[d]) {
ne[++c] = ++d;
} else
d = ne[d];
}
//cout1
for (int i = 0; i < st.size(); i++)
cout << ne[i + 1] - 1 << " ";
cout << "\n";
//kmp
int flag = 0;
c = 0, d = 0;
while (c < s.size()) {
if (d == -1 || s[c] == st[d]) {
c++;
d++;
} else
d = ne[d];
if (d == st.size()) {
cout << c - d ;
return 0;
}
}
cout << -1 << endl;
return 0;
}
4.好中缀
#include <bits/stdc++.h>
using namespace std;
const int M = 1e5 + 1000;
const int N = 35;
int ne[M], ans[M];
int main() {
string s, st;
int n, m, i;
cin >> st;
//next
int c = 0, d = -1;
ne[0] = -1;
while (c < st.size()) {
if (d == -1 || st[c] == st[d]) {
ne[++c] = ++d;
} else
d = ne[d];
}
//solve
int len = st.size();
c = 0, d = ne[len];
while (d > 0) {
ans[c++] = d;
d = ne[d];
}
//cout
n = len - 2 * ans[1];
if (n < 0)
n = 0;
cout << n << endl;
}
5.三元组顺序表表示的稀疏矩阵转置Ⅱ
#include <bits/stdc++.h>
const int N = 1e5 + 10;
using namespace std;
struct node {
int x, y, k, id, p;
} dp[N];
bool cmp(node x, node y) {
if (x.x < y.x)
return 1;
else if (x.x == y.x && x.y < y.y)
return 1;
else
return 0;
}
bool ord(node x, node y) {
return x.id < y.id;
}
int main() {
int n, m, t;
cin >> n >> m >> t;
int x, y, k, i;
for (i = 1; i <= t; i++) {
cin >> x >> y >> k;
dp[i] = {y, x, k, i, 0};
}
sort(dp + 1, dp + 1 + t, cmp);
for (i = 1; i <= t; i++)
dp[i].p = i - 1;
sort(dp + 1, dp + 1 + t, ord);
for (i = 1; i <= t; i++)
cout << dp[i].p << " " << dp[i].x << " " << dp[i].y << " " << dp[i].k << endl;
}
不懂得可以私信我,随时解答。
程序有错误请私信我,以及时改正。感谢!