题目
BaoBao has just found a string s of length n consisting of ‘C’ and ‘P’ in his pocket. As a big fan of the China Collegiate Programming Contest, BaoBao thinks a substring sisi+1si+2si+3 of s is “good”, if and only if si=si+1=si+3= ‘C’ ,and si+2=‘P’, where si denotes the i-th character in string s. The value of s is the number of different “good” substrings in s. Two “good” substrings sisi+1si+2si+3 and sjsj+1sj+2sj+3 are different ,if and only i ≠ j .
To make this string more valuable, BaoBao decides to buy some characters from a character store. Each time he can buy one ‘C’ or one ‘P’ from the store, and insert the character into any position in s.But everything comes with a cost. If it’s the i-th time for BaoBao to buy a character, he will have to spend i - 1 units of value.
The final value BaoBao obtains is the final value of s minus the total cost of all the characters bought from the store. Please help BaoBao maximize the final value.
分析
一共有三个情况可以插入字母
CCC CPC CCP
因为购买字母C,P的价格是在增长的,0,1,2,3,4...
所以如果每次遇到上述三种情况都购买的话,反而会亏本,因为每得到一个CCPC才+1,价格却很贵
所以我们考虑只在原字符串基础上,加一个字母(就支付0元,得到1)
其中特殊情况CCCPC单独处理
可以被CCC识别,而且里面还含有CCPC
如果CCC里插入P就变成CCPCPC,又把后面的CCPC破坏了,在做无用功
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
while(n-->0) {
int len=sc.nextInt();
String s=sc.next();
int count=0;
int flag=0;//flag=1表示可以增加一个
for (int i = 0; i <= len-3; i++) {
if(len-i>=5 && s.substring(i,i+5).equals("CCCPC")) {//特殊情况
count++;
i+=3;
continue;
}
if(len-i>=4 && s.substring(i,i+4).equals("CCPC")) {
count++;
i+=2;
continue;
}
if(flag==0 && len-i>=3) {
String cur=s.substring(i,i+3);
if(cur.equals("CPC") || cur.equals("CCC") || cur.equals("CCP")) {//只要出现一种情况flag就可以置为1
flag=1;
}
}
}
count=flag==1?count+1:count;
System.out.println(count);
}
}
}