【codeforces 576D】LCS Again

给一个串,问有多少和它长度相同的串,使得LCS为l - 1。

#include 
#include 
#include 
#include 
#include 
#define Rep(i, x, y) for (int i = x; i <= y; i ++)
#define Dwn(i, x, y) for (int i = x; i >= y; i --)
#define RepE(i, x) for(int i = pos[x]; i; i = g[i].nex)
using namespace std;
typedef long long LL;
const int N = 100005;
int n, m, p, q, s1[N], s2[N]; char s[N]; LL ans;
int main()
{
	scanf ("%d%d", &n, &m);
	scanf ("%s", s + 1);
	ans = n * (m - 1);
	Rep(i, 1, n - 1) {
		s1[i] = s1[i - 1] + (s[i] != s[i + 1]);
		ans += s1[i] * (m - 1);
	}
	Dwn(i, n, 2) {
		s2[i] = s2[i + 1] + (s[i] != s[i - 1]);
		ans += s2[i] * (m - 1); 
	}
	Rep(i, 1, n - 1) {
		p = max(0, p - 2);
		while (i + p + 2 <= n && s[i + p] == s[i + p + 2]) p ++;
		if (s[i] != s[i + 1]) ans -= p + 1;
		swap(p, q);
	}
	printf("%I64d\n", ans);

	return 0;
}


你可能感兴趣的:(字符串,codeforces)