P15835 [蓝桥杯第一届国际赛] 基因配对 题解
为什么我感觉这题是蓝,是我太菜了吗?
一道 KMP 算法的好题!
化简题目
给定两个字符串 (长)和 (短),判断 是否能与 的某个连续子串配对。
配对规则
- 与 配对;
- 与 配对;
- 与 配对;
- 与 配对;
- 不能倒序(即只能正向匹配)。
如果能配对,就输出最早匹配的起始位置(从 开始计数),否则就是不能配对,输出 。
思路分析
配对映射
- ;
- ;
- ;
- 。
匹配过程
将 转换为配对后的目标串 :。
使用算法
我们接下来可以使用 KMP 算法。
代码实现
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 10;
char l[N], s[N], p[N];
int ans[N];
char match(char c){
if(c == 'A') return 'T';
else if(c == 'T') return 'A';
else if(c == 'G') return 'C';
else if(c == 'C') return 'G';
}
void f(char t[], int m){
ans[0] = 0;
int j = 0;
for(int i = 1; i < m; i++){
while(j && t[i] != t[j]){
j = ans[j - 1];
}
if(t[i] == t[j]){
j++;
}
ans[i] = j;
}
}
int kmp(char a[], int n, char b[], int m){
if(m == 0) return 0;
f(b, m);
int j = 0;
for(int i = 0; i < n; i++){
while(j && a[i] != b[j]){
j = ans[j - 1];
}
if(a[i] == b[j]){
j++;
}
if(j == m){
return i - m + 2;
}
}
return 0;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> l >> s;
int n = strlen(l), m = strlen(s);
for(int i = 0; i < m; i++){
p[i] = match(s[i]);
}
cout << kmp(l, n, p, m);
return 0;
}
恳求
嘤嘤嘤,都一个月没过题解了,就过一次吧(管理员真好看),求各位点赞评论加关注再走吧qwq。