Codeforces Round #625 (Div. 2, based on Technocup 2020 Final Round) C题

Remove Adjacent

You are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string.

In one operation, you can choose some index i and remove the i-th character of s (si) if at least one of its adjacent characters is the previous letter in the Latin alphabet for si. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index i should satisfy the condition 1≤i≤|s| during each operation.

For the character si adjacent characters are si−1 and si+1. The first and the last characters of s both have only one adjacent character (unless |s|=1).

Consider the following example. Let s= bacabcab.

During the first move, you can remove the first character s1= b because s2= a. Then the string becomes s= acabcab.
During the second move, you can remove the fifth character s5= c because s4= b. Then the string becomes s= acabab.
During the third move, you can remove the sixth character s6=‘b’ because s5= a. Then the string becomes s= acaba.
During the fourth move, the only character you can remove is s4= b, because s3= a (or s5= a). The string becomes s= acaa and you cannot do anything with it.
Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.

Input
The first line of the input contains one integer |s| (1≤|s|≤100) — the length of s.

The second line of the input contains one string s consisting of |s| lowercase Latin letters.

Output
Print one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.


题目大意为:给你一个字符串s,如果存在s[i-1]或者s[i+1]为s[i]的字典序的前一个,那么可以把s[i]消除,比如s[i]=b,s[i-1]或s[i+1]如果等于 a,那么s[i]可以消除;

这道题就是一道贪心题;

先从z-b依次把能消除的消除,依据的原理就是字典序大的先消除了,它对后面的字符就不会产生影响;

代码:

#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=1000100;
int main(){
    ios::sync_with_stdio(false);
    int n;
	string s;
	cin>>n>>s;
	int ans=0;
	for(int i=25;i>=1;i--){
		for(int j=1;j<=100;j++){
			for(int k=0;k<s.length();k++){
				if(s[k]=='a'+i&&(s[k-1]=='a'+i-1||s[k+1]=='a'+i-1)){
					ans++,s.erase(k,1),k--;
				}	
			}
		}
	}
	cout<<ans<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值