Count Good Substrings(数学)

D. Count Good Substrings
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".

Given a string, you have to find two values:

  1. the number of good substrings of even length;
  2. the number of good substrings of odd length.
Input

The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.

Output

Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.

Sample test(s)
input
bb
output
1 2
input
baab
output
2 4
input
babb
output
2 5
input
babaa
output
2 7
Note

In example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.

In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.

In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.

Definitions

A substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.

A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.

 

      题意:

      给出一个字符串,这个字符串只由 a,b 组成,连续几个相同则可以合并看成一个,即 abbba 看为 aba,寻找偶数长度的回文串个数和奇数长度的回文串个数。

 

       思路:

       数学。首先要清楚,因为可以合并看成一个,所以首尾相同的两个字母则一定是回文串。偶数长度的回文串首尾两个下标必定是一奇一偶的相同字符组成,奇数长度的回文串必定是下标相同奇偶性的相同字符组成。所以问题就转化为了,求 a 的奇数下标的个数 和 偶数下标的个数,b 也是如此。记得结果要用 long long。

 

        AC:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;

char str[100005];

ll C(ll a) {
    return a * (a - 1) / 2;
}

int main() {

    ll oa = 0, ea = 0, ob = 0, eb = 0;
    scanf("%s", str);

    for (int i = 0; i < strlen(str); ++i) {
        if (str[i] == 'a') {
            if ((i + 1) % 2) ++oa;
            else ++ea;
        } else {
            if ((i + 1) % 2) ++ob;
            else ++eb;
        }
    }

    ll odd = oa * ea + ob * eb;
    ll even = strlen(str) + C(oa) + C(ob) + C(ea) + C(eb);

    printf("%I64d %I64d\n", odd, even);

    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值