P1314 [NOIP 2011 提高组] 聪明的质监员(前缀和)


这道题最核心就是二分W,然后对于每一个W都构建一个前缀和数组,但要注意ans不能开太小,我开INT_MAX都不行,其次就是二分左右端点的变化,如果s-y>0说明满足要求的点多了,这时候我们要提高标准,就是让W增大,及让beign=W+1,反之让end=W-1;如果s=y,此时ans=0;这时候我们可以直接break,因为s和y的差的绝对值不可能比0还小

#include<iostream>
#include<set>
#include<map>
#include<algorithm>
#include<vector>
#include<cmath>
#include<climits>
#include<cstring>
#define int long long
const int N = 1e6;
using namespace std;
char* p1, * p2, buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int read()
{
	int x = 0, f = 1;
	char ch = nc();
	while (ch < 48 || ch>57)
	{
		if (ch == '-')
			f = -1;
		ch = nc();
	}
	while (ch >= 48 && ch <= 57)
		x = x * 10 + ch - 48, ch = nc();
	return x * f;
}
int n, m, s;
int w[N], v[N], l[N], r[N];
int sum1[N],sum2[N];
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m >> s;
	for (int i = 1; i <= n; i++)cin >> w[i] >> v[i];
	for (int i = 1; i <= m; i++)cin >> l[i] >> r[i];
	int begin = 0, end = 1e6;
	int ans = 1e12;//不能开太小
	while (begin <= end) {
		memset(sum1, 0, sizeof(sum1));
		memset(sum2, 0, sizeof(sum2));
		int W = (begin + end) >> 1;
		for (int i = 1; i <= n; i++) {
			if (w[i] >= W) {
				sum1[i] = sum1[i - 1] + 1;
				sum2[i] = sum2[i - 1] + v[i];
			}
			else {
				sum1[i] = sum1[i - 1];
				sum2[i] = sum2[i - 1];
			}
		}
		int y = 0;
		for (int i = 1; i <= m; i++) {
			y += (sum1[r[i]] - sum1[l[i]-1]) * (sum2[r[i]] - sum2[l[i]-1]);
		}
		ans = min(abs(s - y), ans);
		if (s - y > 0)end = W - 1;
		if (s - y < 0)begin = W + 1;
		if (s - y == 0)break;
	}
	cout << abs(ans);
	return 0;
}
posted @ 2025-02-10 20:53  郭轩均  阅读(27)  评论(0)    收藏  举报