贪心策略2

[Algo] 贪心策略2

1. 砍竹子 II

// 1. 砍竹子 II
// https://leetcode.cn/problems/jian-sheng-zi-ii-lcof/description/
int p(int base, int power, int mod) {
    int ans = 1, cur = base;
    while (power > 0) {
        if (power & 1 == 1) {
            ans = (ans * cur) % mod;
        }
        cur = (cur * cur) % mod;
        power >> 1;
    }
    return ans;
}
int cuttingBamboo(int bamboo_len) {
    if (bamboo_len == 2) return 1;
    if (bamboo_len == 3) return 2;
    // 4 --> 2 * 2, 7 --> 3 * 2 * 2
    // 5 --> 2 * 3, 8 --> 3 * 3 * 2  
    // 6 --> 3 * 3, 9 --> 3 * 3 * 3
    int tail = n % 3 == 0 ? 1 : (n % 3 == 1 ? 4 : 2);
    int power = (bamboo_len - (tail == 1 ? 0 : tail)) / 3;
    return p(3, power, MOD) * tail % MOD;
}

2. 无重叠区间

// 2. 无重叠区间
// https://leetcode.cn/problems/non-overlapping-intervals/
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
    int n = intervals.size();
    sort(intervals.begin(), intervals.end(), [](const vector<int> &a, const vector<int> &b) {
        return a[1] < b[1];
    });
    int ans = 0, cur = -50000;
    for (auto &interval : intervals) {
        if (interval[0] >= cur) {
            ans++;
            cur = interval[1];
        }
    }
    return n - ans;
}

3. 最多可以参加的会议数目

// 3. 最多可以参加的会议数目
// https://leetcode.cn/problems/maximum-number-of-events-that-can-be-attended/
int maxEvents(vector<vector<int>>& events) {
    int n = events.size(), ans = 0;
    sort(events.begin(), events.end(), [](const vector<int> &a, const vector<int> &b) {
        return a[0] < b[0];
    });
    int begin_day = events[0][0], end_day = events[0][1];
    for (int i = 1; i < n; i++) if (events[i][1] > end_day) end_day = events[i][1];
    priority_queue<int, vector<int>, greater<int>> min_heap;
    for (int cur = begin_day, i = 0; cur <= end_day; cur++) {
        while (i < n && events[i][0] == cur) min_heap.push(events[i++][1]);
        while (!min_heap.empty() && min_heap.top() < cur) min_heap.pop();
        if (!min_heap.empty()) { min_heap.pop(); ans++; }
    }
    return ans;
}

4. IPO

// 4. IPO
// https://leetcode.cn/problems/ipo/
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
    int n = profits.size();
    vector<vector<int>> projects(n, vector<int>(2));
    for (int i = 0; i < n; i++) {
        projects[i][0] = profits[i];
        projects[i][1] = capital[i];
    }
    sort(projects.begin(), projects.end(), [](const vector<int> &a, const vector<int> &b) {
        return a[1] < b[1];
    });
    priority_queue<int, vector<int>, less<int>> max_heap;
    for (int round = 1, i = 0; round <= k; round++) {
        while (i < n && projects[i][1] <= w) max_heap.push(projects[i++][0]);
        if (!max_heap.empty()) {
            w += max_heap.top();
            max_heap.pop();
        } else {
            break;
        }
    }
    return w;
}
posted @ 2025-06-14 09:02  yaoguyuan  阅读(11)  评论(0)    收藏  举报