65分求助

P1314 [NOIP2011 提高组] 聪明的质监员

zhangchenggang @ 2024-07-10 09:23:35

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define maxnm 200001

int n, m, l = 1, r;
ll s, ans = LLONG_MAX, x;
int L[maxnm], R[maxnm];
int w[maxnm], v[maxnm];
ll sw[maxnm], sv[maxnm];

bool judge(int m) {
    x = 0;
    ll tot = 0;
    memset(sw, 0, sizeof(sw));
    memset(sv, 0, sizeof(sv));
    for(int i = 1; i <= n; i++) {
        if(w[i] >= m) {
            sw[i] = sw[i - 1] + 1;
            sv[i] = sv[i - 1] + v[i];
        } else {
            sw[i] = sw[i - 1];
            sv[i] = sv[i - 1];
        }
    }
    for(int i = 1; i <= m; i++) {
        tot += (ll)(sw[R[i]] - sw[L[i] - 1]) * (sv[R[i]] - sv[L[i] - 1]);
    }
    x = llabs(tot - s);
    ans = min(ans, x);
    if (tot == s) {
        cout << 0;
        exit(0);
    }
    return tot < s;
}

int main() {
    cin >> n >> m >> s;
    ans = s;
    for(int i = 1; i <= n; i++) {
        cin >> w[i] >> v[i];
        r = max(r, w[i]);
    }
    for(int i = 1; i <= m; i++) {
        cin >> L[i] >> R[i];
    }
    r++;
    while(l <= r) {
        int mid = (r - l) / 2 + l;
        if(judge(mid)) r = mid - 1;
        else l = mid + 1;
    }
    printf("%lld", ans);
    return 0;
} 

|