AB-string CodeForces - 1238D(思维)

The string t1t2…tkt1t2…tk is good if each letter of this string belongs to at least one palindrome of length greater than 1.

A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.

Here are some examples of good strings:

tt = AABBB (letters t1t1, t2t2 belong to palindrome t1…t2t1…t2 and letters t3t3, t4t4, t5t5 belong to palindrome t3…t5t3…t5);
tt = ABAA (letters t1t1, t2t2, t3t3 belong to palindrome t1…t3t1…t3 and letter t4t4 belongs to palindrome t3…t4t3…t4);
tt = AAAAA (all letters belong to palindrome t1…t5t1…t5);
You are given a string ss of length nn, consisting of only letters A and B.

You have to calculate the number of good substrings of string ss.

Input
The first line contains one integer nn (1≤n≤3⋅1051≤n≤3⋅105) — the length of the string ss.

The second line contains the string ss, consisting of letters A and B.

Output
Print one integer — the number of good substrings of string ss.

Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s1…s2s1…s2, s1…s4s1…s4, s1…s5s1…s5, s3…s4s3…s4, s3…s5s3…s5 and s4…s5s4…s5.

In the second test case there are three good substrings: s1…s2s1…s2, s1…s3s1…s3 and s2…s3s2…s3.
题意:good string 是源字符串的一个子串。对于一个good string定义是酱紫的,这个字符串中的每一个字母,都位于一个长度大于等于2的回文串中,问有多少个good string。
思路:对于一条字符串来说,一共有n*(n-1)/2个字符串。我们要求有多少个good string,那么我们可以去求有多少个字符串不是good string。相减就可以了。
对于ab,ba这样的来说,就是good string,但是对于abbbbb,bbbbba这样的来说,就不是good string 。
所以我们可以正着求一遍,求出bbbbbba这样的,反着求一遍,求出abbbbb这样的,但是ab或者ba会被减两遍,再遍历一遍加上就好了。
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxx=3e5+100;
char s[maxx];
int n;

int main()
{
	scanf("%d%s",&n,s);
	ll ans=1ll*n*(n-1)/2ll;
	int cnt=1;
	for(int i=1;i<n;i++)
	{
		if(s[i]==s[i-1]) cnt++;
		else
		{
			ans-=(ll)cnt;
			cnt=1;
		}
	}
	cnt=1;
	for(int i=n-2;i>=0;i--)
	{
		if(s[i]==s[i+1]) cnt++;
		else
		{
			ans-=(ll)cnt;
			cnt=1;
		}
	}
	for(int i=1;i<n;i++) if(s[i]!=s[i-1]) ans++;
	cout<<ans<<endl;
}

努力加油a啊,(o)/~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值