String reduction
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1360 | Accepted: 447 |
Description
There is a string of characters 'a' and 'b' with the length of no more than 255 characters. You can perform the substring reduction on the initial string in the following way: a substring "a*a" or "b*b" (where * (asterisk) denotes any character) can be reduces to a substring "*".
The task is to achieve a string of minimal possible length after several substring reductions.
Input
The input contains the initial string.
Output
The output contains a single line with the minimal possible length.
Sample Input
aab
Sample Output
3
Source
Northeastern Europe 2001, Western Subregion
题意:在一个串中形如a*a 或b*b可以变换为a或b,问变换之后最短长度。
由于a*a, b*b之类的字符可以匹配任意字符,那么我们只要从前
向后扫描,如果有相隔的两个字符相同,由于这三个字符能够匹配a,b任意字符,那么我们就可以让这种匹配一直进行
下去,从而将字符串不断的reduction ,只要注意字符串长度的奇偶性就可以了,如此我们可以得到一个很简单的方法
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 7 using namespace std; 8 9 #define N 1100 10 #define INF 0xfffffff 11 #define eps 1e-8 12 13 int main() 14 { 15 char str[N]; 16 17 scanf("%s", str); 18 int ans, len; 19 len = ans = strlen(str); 20 21 for(int i = 0; i + 2 < len; i++) 22 { 23 if(str[i] == str[i+2]) 24 { 25 if(len % 2) 26 ans = 1; 27 else 28 ans = 2; 29 } 30 } 31 printf("%d ", ans); 32 return 0; 33 }