贪心

小红的01串

https://www.nowcoder.com/questionTerminal/d371489291b8455ab5e7fb86a26ee5bc?f=discussion

#include <iostream>
using namespace std;

int main() {
    string str;
    cin >> str;
    int n = 0;
    for (int i = 0; i < str.size() - 3; i++){
        string substr = str.substr(i,3);
        if (substr == "010") {
            if (str.substr(i+2, 3) == "001") {
                str[i+1] = '0';
            } else {
                str[i+2] = '1';
            }
            n++;
        }
        if (substr == "101") {
            if (str.substr(i+2, 3) == "110"){
                str[i+1] = '1';
            } else {
                str[i+2] = '0';
            }
            n++;
        }
    }
    cout << n << endl;
}
// 64 位输出请用 printf("%lld")

 

2.最多的大写字母

有n位字符串(只含大小写字符)。小红可以将任意的大写转成小写,也可以将任意的小写转成大写,求K次操作后(K必须使用完),字符串最多有多少个大写字符

知识点:

1.求大写小写函数 isupper islower

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

int main() {
    string s;
    int K;
    cin >> s >> K;

    int upper = 0, lower = 0;
    for (char c : s) {
        if (isupper(c)) upper++;
        else lower++;
    }

    if (K <= lower) {
        cout << upper + K << endl;
    } else {
        int extra = K - lower;
        if (extra % 2 == 0)
            cout << upper + lower << endl;
        else
            cout << upper + lower - 1 << endl;
    }

    return 0;
}

 

 

3.dd爱科学

https://ac.nowcoder.com/acm/problem/221822

知识点:

1. upper_bound(dp.begin(), dp.end(), x),返回的是迭代器

  • 在 dp 中查找第一个 大于 x 的元素位置;
  • 如果找到了,说明我们可以用 x 替换掉它,目标是让序列的结尾的数更小,这样可以让后续更容易扩展更长的 LIS;
  • 如果没找到(也就是所有元素都 ≤ x),就把 x 插入到 dp 的末尾,表示 LIS 长度 +1;

2.*it是解引用,获得所指向元素的引用

3.

 

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    string s;

    cin >> n >> s;

    vector<int> nums(n);
    for (int i = 0; i < n; ++i) {
        nums[i] = s[i] - 'A'; // 将字母转为数字(0~25)
    }

    vector<int> dp; // 用来维护当前最长的非递减子序列长度(使用贪心+二分)

    for (int x : nums) {
        auto it = upper_bound(dp.begin(), dp.end(), x); // 找到第一个大于x的位置
        if (it == dp.end()) {
            dp.push_back(x);
        } else {
            *it = x;
        }
    }

    int lis_length = dp.size();
    cout << n - lis_length << endl;

    return 0;
}

 

posted @ 2025-06-17 16:43  最近饭吃的很多  阅读(7)  评论(0)    收藏  举报