「CF451D」Count Good Substrings
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:
- the number of good substrings of even length;
- the number of good substrings of odd length.
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’.
Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.
1 |
bb |
1 |
1 2 |
1 |
baab |
1 |
2 4 |
1 |
babb |
1 |
2 5 |
1 |
babaa |
1 |
2 7 |
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组成,而且相同的一段被缩距
那么对于一个子串,缩距之后,只要它头尾是相同的,那么它一定是缩距回文子串
所以只要简单dp即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<iostream> #include<cstdio> #include<cstring> #define ll long long using namespace std; char ch[100005]; ll num[2][2],ans[2]; int main() { scanf("%s",ch); int l=strlen(ch); for(int i=0;i<l;i++) { int x=ch[i]-'a'; ++num[1-i%2][x]; ans[0]+=num[i%2][x]; ans[1]+=num[1-i%2][x]; } printf("%I64d %I64d",ans[0],ans[1]); return 0; } |