Problem
S 串为 DNA 串(即仅包含字母 ACGT
)。有 q 组询问,询问有两种形式:
1 x c
将 S 串中第 x 个位置的字符修改为 c 。2 l r e
,判断 S 截取区间[l, r]
的子串,与 e 串的相同位置字符相同的个数。(其中若 e 串长度不足 r−l+1 ,则通过 e = e+e 的形式复制加长。
限制条件
1 ≤ |S| ≤ 105
1≤q≤105
1≤x≤|S|
1≤l≤r≤|S|
1≤|e|≤10
解法
由于 e 的长度最大为 10 。故考虑通过预处理每种 e 长的统计结果。
dna[ch][pos][start][gap]
表示 起点位置为 start ,每次间隔 gap 个字符的 S 串的子序列,在 pos 位置字符恰好为编号 ch 的个数。
其中 gap 即枚举每种可行的 e 串长度 [1, 10]
。
对于每个 gap ,start 位置的枚举有 [1, gap]
。由于 start = 1+gap 与 start = 1 等效。
通过树状数组加速每次修改操作和询问操作。
代码
#include<bits/stdc++.h>
using namespace std;
#define debug
const int S = 1e5 + 10;
string sgn = "ACGT";
char s[S], e[11], c;
int q, dna[4][S][11][11], typ, x, l, r, rev[128];
inline int lowbit(int x) { return x & -x; }
void add(int ch, int pos, int start, int gap, int w)
{
for(int i=pos;i<S;i+=lowbit(i))
dna[ch][i][start][gap] += w;
}
int get(int ch, int pos, int start, int gap)
{
int ret = 0;
for(int i=pos;i;i-=lowbit(i))
ret += dna[ch][i][start][gap];
return ret;
}
void init()
{
rev['A'] = 0, rev['C'] = 1, rev['G'] = 2, rev['T'] = 3;
int n = strlen(s+1);
for(int ch=0;ch<4;ch++)
for(int gap=1;gap<=10;gap++)
for(int start=1;start<=gap;start++)
for(int pos=start;pos<=n;pos+=gap)
if(s[pos] == sgn[ch])
add(ch, pos, start, gap, 1);
}
int main()
{
scanf(" %s %d", s+1, &q);
init();
while(q-- && scanf("%d", &typ))
{
if(typ == 1)
{
scanf("%d %c", &x, &c);
for(int ch=0;ch<4;ch++)
for(int gap=1;gap<=10;gap++)
for(int start=1;start<=gap;start++)
{
if((x-start) % gap == 0 && s[x] == sgn[ch])
add(ch, x, start, gap, -1);
if((x-start) % gap == 0 && sgn[ch] == c)
add(ch, x, start, gap, 1);
}
s[x] = c;
}
else
{
scanf("%d %d %s", &l, &r, e);
int elen = strlen(e);
int ans = 0;
for(int i=0;i<elen;i++)
{
int start = (l+i)%elen?(l+i)%elen:elen;
int gap = elen;
ans += get(rev[e[i]], r, start, gap) - get(rev[e[i]], l-1, start, gap);
}
printf("%d\n", ans);
}
}
}