CSP 202305-2 垦田计划

 

直接用循环找最长天数的寻常写法只能拿15分,便运行超时结束了

#include <iostream>
using namespace std;
int main(){
    int n,m,k,t=0;
    cin>>n>>m>>k;
    auto*data=new pair<int ,int>[n];
    for(int i=0;i<n;i++){
        cin>>data[i].first>>data[i].second;
        t=t>data[i].first?t:data[i].first;
    }
    while(m>0&&t>k){
        for(int i=0;i<n;i++){
            if(t==data[i].first&&m>=data[i].second){
                data[i].first--;
                m-=data[i].second;
            }
        }
        t=k;
        int temp=t;
        for(int i=0;i<n;i++){
            t=t>data[i].first?t:data[i].first;
        }
        if(temp==t)
            break;
    }
    cout<<t;
}

改用最大堆进行存储,C++的优先队列是堆实现的,这里可以直接用,下面的代码可以拿到70分,依旧运行超时

#include<iostream>
#include<queue>
using namespace std;
int main(){
    int n,m,k,ti,ci;
    priority_queue<pair<int,int>>heap;
    cin>>n>>m>>k;
    while(n--){
        cin>>ti>>ci;
        heap.push({ti,ci});
    }
    while(m>heap.top().second){
        pair<int,int>top=heap.top();
        heap.pop();
        if(top.first==k)
            break;
        top.first--;
        m-=heap.top().second;
        heap.push(top);
    }
    cout<<heap.top().first;
}

换个思路,之前的思路都是一个一个的减的,测试样例最大达到了10亿,不能一个一个的减了,先将所有天数相同的合并在一起并从大到小排序,再将前一个的天数降到后一个天数并相加资源,下面这个代码可以拿到85分,错误

#include<iostream>
#include<map>
using namespace std;
int main(){
    long long n,m,k,ti,ci,t;
    map<long long,long long,greater<>>field;
    cin>>n>>m>>k;
    while(n--){
        cin>>ti>>ci;
        field[ti]+=ci;
    }
    for(auto it=field.begin();it!=field.end();it++){
        if(it== prev(field.end())){
            while(m>=it->second){
                t--;
                m-=it->second;
            }
            break;
        }
        auto next=it;
        next++;
        long long cost=it->second*(it->first-next->first);
        if(m<cost||t==k)
            break;
        t=next->first;
        m-=cost;
        next->second+=it->second;
    }
    t=t>=k?t:k;
    cout<<t;
}
 

经过多次测试,终于发现是当m<cost的时候不应该直接退出,因为m可能可以再减,虽然不能减到下一个,修改后的代码终于可以拿到100分

#include<iostream>
#include<map>
using namespace std;
int main(){
    long long n,m,k,ti,ci,t;
    map<long long,long long,greater<>>field;
    cin>>n>>m>>k;
    while(n--){
        cin>>ti>>ci;
        field[ti]+=ci;
    }
    for(auto it=field.begin();it!=field.end();it++){
        t=it->first;
        if(it== prev(field.end())){
            while(m>=it->second){
                t--;
                m-=it->second;
            }
            break;
        }
        auto next=it;
        next++;
        long long cost=it->second*(it->first-next->first);
        if(m<cost){
            while(m>=it->second){
                t--;
                m-=it->second;
            }
            break;   
        }
        m-=cost;
        next->second+=it->second;
    }
    t=t>=k?t:k;
    cout<<t;
}

猜你喜欢

转载自blog.csdn.net/weixin_62264287/article/details/132719184
CSP