2017秦皇岛CCPC E.String of CCPC(暴力)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cymbals/article/details/82894377

BaoBao has just found a string of length consisting of ‘C’ and ‘P’ in his pocket. As a big fan of the China Collegiate Programming Contest, BaoBao thinks a substring of is “good”, if and only if ‘C’, and ‘P’, where denotes the -th character in string . The value of is the number of different “good” substrings in . Two “good” substrings and are different, if and only if .

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 . But everything comes with a cost. If it’s the -th time for BaoBao to buy a character, he will have to spend units of value.

The final value BaoBao obtains is the final value of minus the total cost of all the characters bought from the store. Please help BaoBao maximize the final value.

观察“CCPC”这个串后发现,因为它自己和自己前后公共部分只有一个“C”,所以不可能出现加一个字符蹦出两个CCPC的情况。
增加字符还有消耗,加一个字符血赚,两个字符无事发生,3个血亏。无论原串如何,都只找个位置加一个字符就行了,这种位置是“CCC”、“CPC”和“CCP”。
但是有的时候加字符会改变已经出现的“CCPC”,比如“CCCPC”,虽然出现了“CCC”,但是在这里加一个“P”变成“CCPCPC”就会破坏原有的“CCPC”,虽然加了字符,也还是只有一个“CCPC”。
因此,所有改变已有“CCPC”的操作必须避免。先预处理出所有“CCPC”的位置,并且计数,然后判断有没有一个不会影响已有“CCPC”的上述三种位置,如有,+1即可。
ac代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

string pa = "CCPC";
string s;
int t, n;
set<int> st;

int check() {
	for(int i = 0; i <= n - 3; i++) {
		bool flag = 0;
		for(int j = i; j < i + 2 && j < n; j++) {
			if(st.count(j)) {
				flag = 1;
				i = j + 2;
				break;
			}
		}
		if(flag) {
			continue;
		}
		string e = s.substr(i, 3);

		if((e == "CCC" || e == "CCP" || e == "CPC")) {
			return 1;
		}
	}
	return 0;
}

int main() {
	ios::sync_with_stdio(0);
	cin >> t;
	while(t--) {
		cin >> n >> s;
		if(n < 3) {
			cout << 0 << endl;
			continue;
		}
		int cnt = 0;
		for(int i = 0; i <= n - 4; i++) {
			bool flag = 0;
			for(int j = 0, temp = i; j < 4; j++, temp++) {
				if(s[temp] != pa[j]) {
					flag = 1;
					break;
				}
			}
			if(!flag) {
				st.insert(i);
				cnt++;
			}
		}
		cnt += check();
		cout << cnt << endl;
		st.clear();
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/Cymbals/article/details/82894377
今日推荐