Fork me on GitHub

[CF-578D(Div 1)] LCS AGAIN

题面

Codeforces-578D

You are given a string S of length n with each character being one of the first m lowercase English letters.

Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.

Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.

Input

The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26).

The second line contains string S.

Output

Print the only line containing the answer.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<bits/stdc++.h>
using namespace std;
char last,la_last;
long long ans = 0,tmp = 0;
inline char next()
{
char c = getchar();
while(!isalpha(c)) c=getchar();
return c;
}

int main(int argc, char *argv[])
{
int n,m;
scanf("%d%d",&n,&m);
ans = 1LL * n * (m-1);
char ret = getchar(),last = next(),la_last = -1;
for (int i = 2; i <= n; i++)
{
char ch = next();
if (ch == la_last) tmp++; else tmp = 0;
if (ch != last) ans += n*(m-1)-tmp-1;
la_last = last;
last = ch;
}
printf("%lld\n",ans);
return 0;
}