uva11491-erasing and winning

Problem Description

Problem URL:Erasing and Winning

Problem Description

Problem Analysis

Obviously,this problem can be solved by using greedy strategy.According to the problem description,we need to erase D numbers,which means there will be N-D numbers left at last.So we can consider to separate two situation to achieve greedy strategy.

Definition
N:A number of N digits
D:Total digits that have to be erased
i:the $i^th$ number in the input
K:The amount of the number that we reserve

The first situation is
$$K+(N-i)>N-D$$
Which means after adding rest digits of certain sequence there will be redundant digits in the answer.In this case,we need to replace a digit that has been added in previous operation.

The second situation is
$$K+(N-i)<N-D$$
In this case,we just need to add the rest digits directly in to the tail of the answer.

But All operation need to follow a rule:
$$K<N-D$$

AC Code

Time Consumption:0ms

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main(){
    int n,d;
    while(~scanf("%d%d",&n,&d) && n && d){
        char a[10010];
        getchar();
        int k=0;
        a[0]='0';
        for(int i=0;i<n;i++){
            char c=getchar();
            while(k>0 && k+(n-i)>n-d && a[k]<c)
                k--;
            if(k<n-d){
                a[++k]=c;
            }
        }
        a[++k]='