C. Good String
Let’s call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.
You are given a string s, you have to delete minimum number of characters from this string so that it becomes good.
Input
The first line contains one integer n (1≤n≤2⋅105) — the number of characters in s.
The second line contains the string s, consisting of exactly n lowercase Latin letters.
Output
In the first line, print one integer k (0≤k≤n) — the minimum number of characters you have to delete from s to make it good.
In the second line, print the resulting string s. If it is empty, you may leave the second line blank, or not print it at all.
Examples
input
4
good
output
0
good
input
4
aabc
output
2
ab
input
3
aaa
output
3
AC:
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
#define ll long long
#define db double
#define FOPEN freopen("C:\\Users\\14016\\Desktop\\cad.txt","r",stdin)
string s;
int main()
{
int n;
// FOPEN;
while(cin>>n)
{
cin>>s;
int flag=0;
int len=s.length();
for(register int i=0; i<s.length()-1; i+=2)
{
if(s[i]==s[i+1]) flag++;
}
if(flag==0&&len%2==0)
{
cout<<0<<endl<<s<<endl;
}
else if(flag==0&&len%2==1)
{
s.erase(len-1);
cout<<1<<endl<<s<<endl;
}
else
{
int flag_=flag;
int cou=0;
char t;
int j;
for(register int i=0; i<s.length()-1; i+=2)
{
if(s[i]==s[i+1])
{
t=s[i];
s.erase(i,1);
cou++;
j=i;
i=i-2;
}
}
len=s.length();
if(len%2==1)
{
s.erase(len-1);
cou++;
cout<<cou<<endl<<s<<endl;
}
else cout<<cou<<endl<<s<<endl;
}
}
}
解题:不用反复去判断哪种删去的方法才是最优方案,例如:aabccddeeffd 这样的字符串,不用去纠结aa是删一个还是两个是最优解,即使aa删去一个导致后面cc dd ee ff 不符合条件,当在操作cc时使用一个操作数,即可使得后面dd ee ff 符合条件,同样总的操作数都为2.