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)/~