[nowcoder-2017 school recruitment real questions] keep the largest number

Niu Ke online programming - keep the largest number

Topic description

Given a decimal positive integer number, choose to remove a part of the numbers from it, and hope that the remaining numbers will form the largest positive integer.

Enter description:

The input is two lines, the first line is a positive integer number, 1 ≤ length(number) ≤ 50000. The second line is the number of digits to be removed cnt 1 ≤ cnt < length(number).

Output description:

Output the retained results.

Example 1

enter

325 1

output

35

answer

Method 1. Because you want the last remaining number to be as large as possible, greedily find a certain number of digits from the front to the back and delete the number, but this requires O(n*m) (n is the total number of digits) , m is the number of deletions). We can use a stack to achieve O(n) time complexity: traverse each bit, pop it when it can be deleted and the number in the stack is smaller than the current number, until the number in the stack is larger than the current number, or When the stack is empty, push the current number onto the stack. If all numbers need to be deleted when they have been put on the stack, delete them from the top of the stack.

sta = []
#num = '0123456789'

s = input()
n = m = int(input())

for i in s:
    #while len(sta) != 0 and num.index(sta[-1]) < num.index(i) and m > 0:
    while len(sta) != 0 and sta[-1] < i and m > 0:
        m -= 1
        sta.pop()
    sta.append(i)
    
print (''.join(sta[:(len(s) - n)]))

Method 2.

Greedily search from the beginning to the back to find two adjacent numbers that the previous number is smaller than the next number, delete the previous number, when all such cases are deleted, the number of numbers cnt is not 0, delete the remaining number of cnt from the back. number.

(If you choose to delete all 0s, then delete all 1s, and then delete all 2s, this greedy strategy is wrong. For example: 3450 1, the correct result should be 450)


#include<bits/stdc++.h>

using namespace std;

const int maxn = 50005;

char s[maxn];

int stk[maxn];

 

int main(){

    int cnt,top = -1;

    scanf("%s %d",s,&cnt);

    int len = strlen(s);

    for (int i = 0;i < len - 1;i++){

        if (s[i] >= s[i + 1] || !cnt){

            stk[++top] = s[i] - '0';

        }else if (cnt && s[i] < s[i + 1]){

            cnt--;

            while (cnt && top >= 0 && stk[top] < s[i + 1] - '0'){

                top--;

                cnt--;

            }

        }

    }

    stk[++top] = s[len - 1] - '0';

    while (cnt){

        cnt--;

        top--;

    }

    for (int i = 0;i <= top;i++){

        printf("%d",stk[i]);

    }

    printf("\n");

    return 0;

}

//https://www.cnblogs.com/zzy19961112/p/8525873.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324935158&siteId=291194637