codeforce Gym - 101061E (ST 表)

46 篇文章 0 订阅
6 篇文章 0 订阅

codeforce Gym - 101061E

题目

给一个最大 1000 位的数 n,有可能有前导零,再给一个整数 m,问从 n 中删去 m 位数字,能得到最大最小的数是多少。

分析

这个题跟 hdu 3486 差不多,只不过要多求一个最小值,还要考虑前导零。

分开讨论,两种情况最大最小,先说最小。

  1. 删去数字比非前导零部分长————直接删去所有非零部分
  2. 删去数字没非前导零部分长————从非零部分找能留下的最小值。
    维护一个区间 (s, e),每次用 st 表从区间找最小值,跟新区间
    s = 最小值所在下标 + 1
    e = e + 1
    注意 : 用 s t st st表打表区间最值的时候,遇到相同值要尽可能取左边的值。

求最大同理。

我好像写的麻烦了。。。
这个按贪心做:https://blog.csdn.net/FeBr2/article/details/52218213

代码

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define d(x) cout<<(x)<<endl
const int N = 1e5 + 10;

int t, n, len, c1, c2;
char a[N];
int st1[N][30], st2[N][30];

void init(){
    memset(st1, 0, sizeof(st1));
    memset(st2, 0, sizeof(st2));
    for(int i = 1; i <= len; i++){
        st1[i][0] = st2[i][0] = i;
    }
    for(int j = 1; (1<<j) <= len; j++){
        for (int i = 1; i + (1 << j) - 1 <= len; i++){
            int x = st1[i][j - 1], y = st1[i + (1 << (j-1))][j - 1];
            st1[i][j] = a[x] <= a[y] ? x : y;   // 最小
            x = st2[i][j - 1], y = st2[i + (1 << (j-1))][j - 1];
            st2[i][j] = a[x] >= a[y] ? x : y;   // 最大
        }
    }
}

int ask1(int l, int r){
    int k = log2(r-l+1);
    int x = st1[l][k], y = st1[r - (1 << (k)) + 1][k];
    return a[x] <= a[y] ? x : y;
}

int ask2(int l, int r){
    int k = log2(r-l+1);
    int x = st2[l][k], y = st2[r - (1 << (k)) + 1][k];
    return a[x] >= a[y] ? x : y;
}

void cal1(){
    if(n >= c2){
        for(int i = 1; i <= len-n; i++){
            printf("%c", a[i]);
        }
    }else{
        for(int i = 1; i <= c1; i++){
            printf("%c", a[i]);
        }
        int num = c2 - n;
        int s = c1 + 1;
        int e = len - num + 1;
        while(e <= len){
            int k = ask1(s, e);
            // cout << s << " " << e << endl;
            printf("%c", a[k]);
            s = k+1;
            e++;
        }
    }
    printf("\n");
}

void cal2(){
    if(n <= c1){
        for(int i = n+1; i <= len; i++){
            printf("%c", a[i]);
        }
    }else{
        n -= c1;
        int s = c1 + 1;
        int e = c1+n+1;
        while(e <= len){
            int k = ask2(s, e);
            // cout << s << " " << e << endl;
            printf("%c", a[k]);
            s = k+1;
            e++;
        }
    }
    printf("\n");
}

int main()
{
    scanf("%d", &t);
    getchar();
    while(t--){
        scanf("%s%d", a+1, &n);
        len = strlen(a+1);
        init();
        int k = 0;              // 最后一个 0
        for (int i = 1; i <= len; i++){
            if(a[i] != '0'){
                k = i - 1;
                break;
            }
        }
        c1 = k - 0, c2 = len - c1;
        cal1();
        cal2();
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值