Cod sursă (job #821817)

Utilizator avatar Emanuel Emanuel Sarbu Emanuel IP ascuns
Problemă Ștampile Compilator cpp-32 | 1,67 kb
Rundă Arhiva de probleme Status evaluat
Dată 29 apr. 2025 23:05:29 Scor 10
#include <bits/stdc++.h>
using namespace std;
using pii = pair<int,int>;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    freopen("stampile.in","r",stdin);
    freopen("stampile.out","w",stdout);

    int N,M;
    cin>>N>>M;
    vector<int> S(N+1);
    for(int i=1;i<=N;i++) cin>>S[i];

    struct Interval{ int A,B; int V; };
    vector<Interval> I(M);
    vector<vector<int>> startAt(N+2);
    for(int j=0;j<M;j++){
        cin>>I[j].A>>I[j].B>>I[j].V;
        startAt[I[j].A].push_back(j);
    }

    // max-heap by B
    priority_queue<pair<int,int>> pq;
    long long ans=0;
    // remaining capacity
    vector<int> rem(M);
    for(int j=0;j<M;j++) rem[j]=I[j].V;

    for(int i=1;i<=N;i++){
        // add intervals that start here
        for(int j: startAt[i]){
            if(rem[j]>0)
                pq.emplace(I[j].B, j);
        }
        // remove expired intervals
        while(!pq.empty() && pq.top().first < i)
            pq.pop();

        // satisfy S[i] stamps
        for(int need=S[i]; need>0; need--){
            // pick the interval reaching farthest
            while(!pq.empty() && rem[pq.top().second]==0)
                pq.pop();
            if(pq.empty()){
                cout<<-1<<"\n";
                return 0;
            }
            auto [b,j] = pq.top();
            // use it once
            rem[j]--;
            ans++;
            // if still has capacity, keep it in heap
            if(rem[j]>0){
                // nothing to do, it remains valid with same B
            } else {
                pq.pop();
            }
        }
    }

    cout<<ans<<"\n";
    return 0;
}