题解 P7767 DNA
原题链接
思路
线性 DP。
令
考虑状态转移方程,当
显然,若使序列全部变为
若使序列全部变为
同理,
最后,注意初始化即可。
代码
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define db double
#define gc getchar
#define pc putchar
#define fs first
#define sc second
using namespace std;
ll read()
{
ll x=0,f=1;
char ch=gc();
while(ch<'0'||ch>'9')
{
if(ch=='-')f=-1;
ch=gc();
}
while(ch>='0'&&ch<='9')
x=x*10+(ch^48),ch=gc();
return x*f;
}
void print(ll x)
{
if(x<0)pc('-'),x=-x;
if(x>9)print(x/10);
pc(x%10+48);
}
const int N=1e6+5;
int n,f[N],g[N];
char s[N];
int main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
n=read(),scanf("%s",s+1);
if(s[1]=='A')f[1]=0,g[1]=1;
if(s[1]=='B')f[1]=1,g[1]=0;
for(int i=2;i<=n;i++)
{
if(s[i]=='A')
f[i]=f[i-1],g[i]=min(g[i-1]+1,f[i-1]+1);
if(s[i]=='B')
f[i]=min(f[i-1]+1,g[i-1]+1),g[i]=g[i-1];
}
print(f[n]);
return 0;
}