CodeForces 451D Count Good Substrings

Count Good Substrings
Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

Description

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 Input

Input
bb
Output
1 2
Input
baab
Output
2 4
Input
babb
Output
2 5
Input
babaa
Output
2 7

Hint

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.

 

 

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
long long cal(long long a)
{
    return a*(a-1)/2;
}
int main()
{
    char str[100005];
    long long odda,oddb,evea,eveb;
    odda=oddb=evea=eveb=0;
    scanf("%s",str);
    for(int i=0;i<strlen(str);i++)
    {
        if(str[i]=='a')
        {
            if(i&1)
            {
                //cout<<i<<endl;
                evea++;
            }else{
                odda++;
            }
        }else{
            if(i&1)
            {
                eveb++;
            }else{
                oddb++;
            }

        }
    }
    long long anseve=odda*evea+oddb*eveb;
    long long ansodd=cal(odda)+cal(evea)+cal(oddb)+cal(eveb)+strlen(str);
    printf("%I64d %I64d",anseve,ansodd);
}
View Code

 

这道题精彩的地方在于只有两个字符,那么任意一个子串,如果该子串的首尾相同的话,那么这个子串一定是一个good string,这个我没有想严格的证明,但是这是显然成立的。

想明白这个特点就简单了:分别统计 奇数位上的a,b的个数odda,oddb.偶数位上的a,b的个数evea,eveb。

然后偶数的子串的来源:odda*evea+oddb*eveb.:不用考虑先后关系,任何一个奇数位上和一个偶数位上的同一字符之间的字符个数一定是偶数,显然成立(个数=|奇数-偶数|+1,显然是偶数)

奇数长度的子串的来源:组合数(odda,2)=odd*(odda-1)/2!+(其他三个数求组合数)+str.length().因为单独一个字符也是个奇数长度的good string。原理跟上面所说的差不多。

posted @ 2016-05-13 17:13  超级学渣渣  阅读(240)  评论(0编辑  收藏  举报