HDU 3183 A Magic Lamp(贪心+stack)

F - A Magic Lamp

Time Limit: 1000 MS Memory Limit: 32768 KB

64-bit integer IO format: %I64d , %I64u Java class name: Main

[Submit] [Status]

Description

Kiki likes traveling. One day she finds a magic lamp, unfortunately the genie in the lamp is not so kind. Kiki must answer a question, and then the genie will realize one of her dreams. 
The question is: give you an integer, you are allowed to delete exactly m digits. The left digits will form a new integer. You should make it minimum.
You are not allowed to change the order of the digits. Now can you help Kiki to realize her dream?

Input

There are several test cases.
Each test case will contain an integer you are given (which may at most contains 1000 digits.) and the integer m (if the integer contains n digits, m will not bigger then n). The given integer will not contain leading zero.

Output

For each case, output the minimum result you can get in one line.
If the result contains leading zero, ignore it. 

Sample Input

178543 4 
1000001 1
100001 2
12345 2
54321 2

Sample Output

13
1
0
123
321

题意:

给定一个少于1000位的数,删掉m个后的最小数。

思路:

贪心,从头开始遍历,若当前数比前一个小,则向前删除,直到遇到小于当前数的数停止,一直到最后。

例如:178643    ->    178643    ->    178643    ->    178643    ->    13    

后进先出,用stack很方便

注意:当栈为空时,不可进行栈顶元素top()访问,否则程序崩溃,Runtime Errror,因为这个浪费了好长时间……

测试样例:1 1     ans: 0

代码:

#include <cstdio>
#include <iostream>
#include <string>
#include <stack>
using namespace std;

int main()
{
    string str;
    int num;
    while(cin >> str >> num)
    {
        stack<int>a;
        stack<int>b;
        a.push(str[0]-'0');
        for(int i=1; i<str.size(); i++){
            int cur = str[i] - '0';
            if(cur >= a.top()) a.push(cur);
            else{
                while(!a.empty() && a.top() > cur && num){
                    a.pop();
                    num --;
                }
                a.push(cur);
            }
        }
        ///若遍历结束后num>0,则从后面删掉剩余的num个
        while(!a.empty() && num){
            a.pop();
            num --;
        }
        while(!a.empty()){    ///将a倒置,以便正序输出
            b.push(a.top());
            a.pop();
        }
        ///将前面的零删掉
        if(!b.empty())    ///注意此处,当b为空时不能访问 b.top(),否则程序崩溃
            while(b.top() == 0 && b.size()!=1) b.pop();
        if(b.size() == 0) cout << "0" << endl;
        else{
            while(!b.empty()){
                printf("%d", b.top());
                b.pop();
            }
            cout << endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/a_thinking_reed_/article/details/80286323