Cod sursă (job #821819)

Utilizator avatar Emanuel Emanuel Sarbu Emanuel IP ascuns
Problemă Ștampile Compilator cpp-32 | 1,28 kb
Rundă Arhiva de probleme Status evaluat
Dată 29 apr. 2025 23:09:13 Scor 0
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

struct Interval { int A, B; ll V; };

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

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

    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_j
    priority_queue<pair<int,int>> pq;
    vector<ll> rem(M);
    for(int j=0;j<M;j++) rem[j]=I[j].V;

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

        ll need = S[i];
        while(need>0){
            if(pq.empty()){
                cout << -1 << "\n";
                return 0;
            }
            auto [b,j] = pq.top();
            ll use = min(need, rem[j]);
            need -= use;
            rem[j] -= use;
            ans += use;
            if(rem[j]==0) pq.pop();
        }
    }

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