其他分享
首页 > 其他分享> > 移除相邻(string操作+implement)

移除相邻(string操作+implement)

作者:互联网

https://codeforces.com/contest/1321/problem/C

题意:给出一个字符串,消除规则:某个字符比左边相邻或右边相邻字符大1,则该字符可以删除,比如ba,b可以删除。

问最多可以删除多少个字符。

解法:贪心从字符z开始删除,判断能否从左边找和右边找比该字符小1的字符,找到则删除该字符,并继续从头开始枚举该字符,比如cbbbbcaaca。

//#include<bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string.h>
#include <vector>
typedef long long ll ;
#define int ll
#define mod 1000000007
#define gcd __gcd
#define rep(i , j , n) for(int i = j ; i <= n ; i++)
#define red(i , n , j)  for(int i = n ; i >= j ; i--)
#define ME(x , y) memset(x , y , sizeof(x))
//ll lcm(ll a , ll b){return a*b/gcd(a,b);}
ll quickpow(ll a , ll b){ll ans=1;while(b){if(b&1)ans=ans*a%mod;b>>=1,a=a*a%mod;}return ans;}
//int euler1(int x){int ans=x;for(int i=2;i*i<=x;i++)if(x%i==0){ans-=ans/i;while(x%i==0)x/=i;}if(x>1)ans-=ans/x;return ans;}
//const int N = 1e7+9; int vis[n],prime[n],phi[N];int euler2(int n){ME(vis,true);int len=1;rep(i,2,n){if(vis[i]){prime[len++]=i,phi[i]=i-1;}for(int j=1;j<len&&prime[j]*i<=n;j++){vis[i*prime[j]]=0;if(i%prime[j]==0){phi[i*prime[j]]=phi[i]*prime[j];break;}else{phi[i*prime[j]]=phi[i]*phi[prime[j]];}}}return len}
#define SC scanf
#define INF  0x3f3f3f3f
#define PI acos(-1)
#define pii pair<int,int>
#define fi first
#define se second
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
using namespace std;
const int N = 1e6+100;
const int maxn = 1e2+9;
int flag ;
char c = 'z';
string a ;

bool search(int i){
    if(i - 1 >= 0 && a[i - 1] == c - 1){
        a.erase(a.begin() + i);
        return true;
    }
    if(i + 1 < a.size() && a[i + 1] == c - 1){
        a.erase(a.begin() + i);
        return true;
    }
    return false;
}

void solve(){
    int n ;
    cin >> n ;
    cin >> a ;
    while(c > 'a'){
        flag = 0 ;
        rep(i , 0 , a.size()){
            if(a[i] == c){
                if(search(i)){
                    flag = 1 ;
                }
            }
        }
        c--;
        if(flag) c++;
    }
    cout << n - a.size() << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    //int t ;
    //cin >> t ;
    //while(t--){
        solve();
    //}
}

 

标签:return,string,int,ll,ans,移除,implement,include,define
来源: https://www.cnblogs.com/nonames/p/12394364.html