题目大意:
现在有一个长度为n的串S,其中每一个字母都是前m个小写字母
计算有多少个不同的长度为n的T(其中T也是由前m个小写字母组成),并且S与T的LCS为n-1
LCS就是同时存在于S和T的最长子序列
解题思路:
把相邻并且相同的字母视为一个块,每个块对答案贡献为
n
×
m
n\times m
n×m
我们发现当一个串为:
a
b
a
b
abab
abab时,答案是会重复的,也就是隔开字母相等也是会有重复的,接着我们可以推出如果相隔
x
x
x个则重复
C
x
2
C^2_x
Cx2次
然后就可以求得答案
A c c e p t e d c o d e : Accepted\ code: Accepted code:
#include<cstdio>
#define ll long long
using namespace std;
const ll N = 100005;
ll n, m, ans, k;
char s[N];
int main() {
scanf("%lld %lld", &n, &m);
scanf("%s", s+1);
ans = 1;
for (ll i = 2; i <= n; ++i)
ans += (s[i] != s[i-1]);
ans *= n * m - n; k = 1;
for (ll i = 2;i <= n; ++i)
if (k == 1) k += (s[i] != s[i-1]);
else if(s[i] == s[i-2]) ++k;
else {
ans -= k * (k-1) / 2;
k = (s[i] != s[i-1]) + 1;
}
ans -= k * (k-1) / 2;
printf("%lld", ans);
}