GESP四级编程题

· · 题解

思路

由于第 i 天只要大于等于 i 道题的题库,所有只要找到大于等于 i,且最少的题库即可。

贪心的思想,让每次的浪费题目最少即全局最优。

实现方式多种多样,数组排序模拟,小根堆 ( 二分查找用STL 和手写都会 TLE ),都可以 (n \le 10^6),但是数组模拟时要注意天数和题库数分开,不然容易弄混。

代码

#include<bits/stdc++.h>
using namespace std;
int a[1000010], n, k, ans; 
int main(){
    cin >> n;
    for(int i = 0;i < n;i ++){
        cin >> a[i];
    }
    sort(a, a + n);//排序
    for(int i = 1;k < n;){
        if(a[k] < i){
            k++;//不足i就往后找
        }else{
            ans++, k++, i++;//成功匹配
        }
    }
    cout << ans;
    return 0;
} 

或者

#include<bits/stdc++.h>
using namespace std;
int a[1000010], n, ans, i=1; 
priority_queue<int,vector<int>,greater<int> >q;
int main(){
    cin >> n;
    for(int i = 0;i < n;i ++){
        int x;
        cin >> x;
        q.push(x);//小根堆自动排序
    }
    while(!q.empty()){
        if(q.top() < i)q.pop();//不足i就往后找
        else{
            i++, q.pop(), ans++;//成功匹配
        }
    }
    cout << ans;
    return 0;
} 

或者

#include<bits/stdc++.h>
using namespace std;
vector<int>a; 
int n, cnt, ans;
int main(){
    cin >> n;
    for(int i = 0; i < n; i ++){
        int x;
        cin >> x;
        a.push_back(x);
    }
    sort(a.begin(), a.end());//二分前先排序
    for(int i = 1; cnt <= n; i ++){
        if(lower_bound(a.begin(), a.end(), i) != a.end()){//找得到
            cnt ++;//成功匹配
            a.erase(lower_bound(a.begin(), a.end(), i));
            ans ++;
        }else break;//找完了
    }
    cout << ans;
    return 0;
}
//会 TLE ,只有 25 分

这个也一样。

#include<bits/stdc++.h>
using namespace std;
vector<int>a; 
int n, cnt, ans;
int main(){
    cin >> n;
    for(int i = 0; i < n; i ++){
        int x;
        cin >> x;
        a.push_back(x);
    }
    sort(a.begin(), a.end());//二分前先排序
    for(int i = 1; cnt <= n; i ++){
        int l = 0, r = a.size() - 1, mid;
        while(l < r){
            mid = l + r >> 1;
            if(a[mid] < i)l = mid + 1;
            else r = mid;
        }//正常二分模板
        if(a[l] >= i){
            cnt++;
            a.erase(a.begin() + l);//用完了删掉
        }
        else break;
    }
    cout << cnt;
    return 0;
}

可以点个赞吗 QAQ。