P1106 删数问题

P1106 删数问题

题目链接
在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
inline int read() {
    int x = 0, f = 1;
    char c = getchar();
    while (c < '0' || c > '9') {
        if (c == '-')
            f = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9')
        x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
    return x * f;
}

string str;
int k;
int cnt = -1, len = 0;
char c[300];
int main() {
    cin >> str >> k;
    int i = 0;
    while (str[i] == '0') {
        i++;
    }
    for (; i < str.size(); ++i) {
        while (len < k && str[i] < c[cnt] && cnt != -1) {
            cnt--, len++;
        }
        c[++cnt] = str[i];
    }
    i = 0;
    while (c[i] == '0') {
        i++;
    }
    int flag = 0;
    for (; i < str.size() - k; ++i) {
        cout << c[i];
        flag = 1;
    }
    if (flag == 0)
        cout << "0" << endl;

    return 0;
}

#include <stdio.h>
#include <string.h>
char c[260];
int main(){
    int len,i,j,s;
    scanf("%s%d",c,&s);
    len=strlen(c);
    while(s--){
        for(i=0;i<=len-2;i++)
            if(c[i]>c[i+1]){
                for(j=i;j<=len-2;j++)
                    c[j]=c[j+1];
                break;
            }
        len--;//此处位置写错,之前写在if内部
    }
    i=0;
    while(i<=len-1&&c[i]=='0')i++;//处理前导0 
    if(i==len)printf("0");
    else
        for(j=i;j<=len-1;j++)
            printf("%c",c[j]); 
    return 0;
} 

题解:一个规则,就是当前数位要不要删除,取决于下标为i的数字有没有比下标为i-1的数字小,如果是,就把下表为i-1的数字删去,如此往复,得到了一个前半段不下降的子序列,k如果大一点的话就能得到一个全段不下降子序列。要留意的点就是如果你删除完后得到的结果有前导零,也得删除,但是当结果就是一个0的时候就不要删前导零了,会把结果删没了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值