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;
}

 

 

你可能感兴趣的:(substring)