NC14367. String of CCPC
描述
输入描述
There are multiple test cases. The first line of the input contains an integer T, indicating the number of test cases. For each test case:The first line contains an integer n (1 ≤ n ≤ 2 ×105) indicating the length of strings.The second line contains the string s (|s| = n)consisting of 'C' and 'P'.It's guaranteed that the sum of n over all test cases will not exceed 106.
输出描述
For each test case output one line containing one integer, indicating the maximum final value BaoBao can obtain.
示例1
输入:
3 3 CCC 5 CCCCP 4 CPCP
输出:
1 1 1
说明:
For the first sample test case, BaoBao can buy one 'P' (cost 0 value) and change to "CCPC". So the final value is 1 - 0 = 1.C++14(g++5.4) 解法, 执行用时: 159ms, 内存消耗: 776K, 提交时间: 2020-02-10 16:25:37
#include<iostream> #include<cstdio> using namespace std; int t,n; string s; int ans,flag; int main(void){ cin>>t; while(t--){ ans = flag = 0; cin>>n; cin>>s; for(int i = 0;i<n;++i){ if(s.substr(i,4) == "CCPC"){ ++ans; i+=2; continue; } if(!flag && (s.substr(i,3)=="CCC" || s.substr(i,3) == "CCP" || s.substr(i,3) == "CPC")){ if(s.substr(i,3) == "CCC" && s.substr(i+1,4) == "CCPC") continue; ++ans; flag = 1; } } cout<<ans<<endl; } return 0; }
C++(clang++ 11.0.1) 解法, 执行用时: 74ms, 内存消耗: 876K, 提交时间: 2022-10-16 14:15:52
#include<bits/stdc++.h> using namespace std; void slove(){ int n; cin>>n; string s; cin>>s; int cnt=0; for(int i=0;i<n-3;i++){ string temp=s.substr(i,4); if(temp=="CCPC"){ cnt++; s[i+1]=s[i+2]='x'; } } if(s.find("CCC")!=-1||s.find("CPC")!=-1||s.find("CCP")!=-1)cnt++; cout<<cnt<<endl; return; } int main(){ int t; cin>>t; while(t--){ slove(); } return 0; }