2 条题解

  • 0
    @ 2025-5-19 23:21:58

    贪心+单调栈使用stack:

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        string a;    // 原始高精度数字字符串
        int s;       // 需要删除的位数
        cin >> a >> s;
    
        int rem = s;            // 剩余可删除次数
        stack<char> st;         // 单调栈:维护当前最优前缀
    
        // 遍历每一位数字,尽可能在前面删除大数以获得更小结果
        for (char c : a) {
            // 如果当前栈顶比新数字大,并且还可以删除,就弹出栈顶
            while (rem > 0 && !st.empty() && st.top() > c) {
                st.pop();
                --rem;
            }
            st.push(c);
        }
        // 如果遍历结束后仍有删除次数,继续从末尾删除
        while (rem > 0 && !st.empty()) {
            st.pop();
            --rem;
        }
    
        // 把栈中字符取出组成结果(此时是倒序)
        string res;
        res.reserve(a.size() - s);
        while (!st.empty()) {
            res.push_back(st.top());
            st.pop();
        }
        reverse(res.begin(), res.end());
    
        // 去除前导零,但至少保留一位
        int pos = 0;
        while (pos + 1 < (int)res.size() && res[pos] == '0') {
            ++pos;
        }
    
        cout << res.substr(pos) << "\n";
        return 0;
    }
    
    
    • 0
      @ 2024-4-21 0:17:23

      贪心+单调栈:

      #include <bits/stdc++.h>
      using namespace std;
      
      int main() {
          string n;
          int s;
          cin >> n;  // 输入原始数字字符串
          cin >> s;  // 输入需要删除的数字个数
      
          string result;  // 存储最终结果
          int toRemove = s;  // 需要删除的总数
      
          for (char digit : n) {
              // 当栈不为空,且栈顶元素大于当前元素,且还需要删除的数量大于0时
              while (!result.empty() && result.back() > digit && toRemove > 0) {
                  result.pop_back();  // 弹出栈顶元素
                  toRemove--;  // 已删除元素数减1
              }
              result.push_back(digit);  // 将当前数字加入到结果中
          }
      
          // 最终结果长度应该是原长度减去需要删除的个数
          result.resize(n.length() - s);
      
          // 输出结果(可能需要去除前导零)
          int start = 0;  // 找到第一个非零字符的位置
          while (start < result.size() && result[start] == '0') start++;
          if (start == result.size()) {
              cout << "0\n";  // 全部都是零的情况
          } else {
              cout << result.substr(start) << endl;  // 输出最终的字符串
          }
      
          return 0;
      }
      
      
      • 1

      信息

      ID
      416
      时间
      1000ms
      内存
      128MiB
      难度
      9
      标签
      递交数
      62
      已通过
      7
      上传者