2017 CCPC秦皇岛E题String of CCPC java

题目

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);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值