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, BBBAare not.

Here are some examples of good strings:

  • tt = AABBB (letters t1t1, t2t2 belong to palindrome t1…t2t1…t2 and letters t3t3, t4t4, t5t5belong 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.

题意:给你一个字符串让你判断有多少个合法的回文串,所有的字符都有A和B组成,输出其数量;

思路:合法的 = 用总方案数  减去  不合法的  ;例“AAAB......BBAA” 这个字符串,长度为n,总情况为n * (n-1) / 2,不合法的只有四种 ABBB... || BAAA... || ... AAAB  || ...BBBA都是不合法的;其他的都是合法的,所以只需要正着遍历一遍和倒着遍历一遍即可代码如下:

代码:

//合法的=总共-不合法的
//ABBB...||BAAA...||...AAAB||...BBBA都是不合法的
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char s[400000],b[400000];
int main()
{
    int n,t=0;
    scanf("%d",&n);
    scanf("%s",s);
    long long sum=1ll*n*(n-1)/2;  /*记录总共有多少种。注意一定要转
                                    化成 long long 型,因为没有转换一直错,
                                    以后直接全部用long long 型;*/
    for(int i=1; i<n; i++)        /*正序遍历一遍减去不合法的;*/
    {
        if(s[i]==s[i-1])
            continue;
        sum++;    /*这点很好理解,例如AB这是正序,不合法需要
                    把他减去,当你倒过来时就变成BA,不合法还要减
                    去ta,所以需要减去两次,所以要加1;*/
        sum=sum-i+t;/*例ABBBBB,AB,ABB,ABBB,ABBBB,ABBBBB都是
                     不满足的只需要让最后一个B的下边减去A的下标即可*/
        t=i;
    }
    int k=0;
    for(int i=n-1; i>=0; i--)//倒着存放
        b[k++]=s[i];
    t=0;
    for(int i=1; i<n; i++)//倒序遍历一遍减去不合法的
    {
        if(b[i]==b[i-1])
            continue;
        sum=sum-i+t;//同上
        t=i;
    }
    printf("%lld\n",sum);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值