跳到正文

题解

题解:P4181 [USACO18JAN] Rental Service S

Pratty约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
题目
P4181

版本

  1. v1当前

花了两个小时才通过,必须写题解泄愤。

很容易想到的一个性质:对于产奶少的牛,卖给邻居最合适。

推得:一定存在一个分界点,使得产奶比该牛少的牛(包括该牛)全部卖给邻居,产奶比该牛多的牛全部用于挤奶。

因此我们只需要枚举这个分界点,通过前缀和预处理出卖出和供应商店的价钱即可。

预处理出供应商店的金额:

C++
for (int i = 1; i <= m; i++) {
	sum[i] = sum[i - 1] + 1LL * a[i].num * a[i].val;
}

卖出的金额:

C++
for (int i = 0; i <= n; i++) {//1~i卖给邻居,i+1~n供应商店
	sumr += r[i];
	...
}

由于每次供应商店的时候,一定都是从给的价格最高的开始供应,所以我们每次少一头牛产奶,少了多少加仑牛奶就从价格最低的开始扣除多少加仑。我们可以用一个变量记录 cc 数组的后缀,然后每次减去 cic_i 的值,把相应的差从价格最低的开始扣掉:

C++
sumc -= c[i];
while (top > 0) {
	if (numa < sumc) {
		break;
	}
	if (numa - a[top].num >= sumc) {
		numa -= a[top].num;
		top--;
	} else {
		a[top].num -= numa - sumc;
		numa = sumc;
		break;
	}
}

最后将卖出和产奶的金额加起来,更新答案:

C++
long long cst = a[top].num * a[top].val;
if (top > 0) cst += sum[top - 1];
ans = max(ans, sumr + cst);

最终代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1100000;
int n, m, R;
int c[N], p[N], q[N], r[N];
long long ans;
long long sumr, sumc, numa;
long long sum[N];
struct node {
	int val, num;
} a[N];
bool cmp(int x, int y) {
	return x < y;
}
bool cmp2(node x, node y) {
	return x.val > y.val;
}
bool cmp3(int x, int y) {
	return x > y;
}
int main() {
	scanf("%d%d%d", &n, &m, &R);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &c[i]);
		sumc += c[i];
	}
	for (int i = 1; i <= m; i++) {
		scanf("%d%d", &a[i].num, &a[i].val);
		numa += a[i].num;
	}
	for (int i = 1; i <= R; i++) {
		scanf("%d", &r[i]);
	}
	sort(c + 1, c + n + 1, cmp);
	sort(a + 1, a + m + 1, cmp2);
	sort(r + 1, r + R + 1, cmp3);
	for (int i = 1; i <= m; i++) {
		sum[i] = sum[i - 1] + 1LL * a[i].num * a[i].val;
	}
	int top = m;
	for (int i = 0; i <= n; i++) {//1~i卖给邻居,i+1~n供应商店
		sumr += r[i];
		sumc -= c[i];
		while (top > 0) {
			if (numa < sumc) {
				break;
			}
			if (numa - a[top].num >= sumc) {
				numa -= a[top].num;
				top--;
			} else {
				a[top].num -= numa - sumc;
				numa = sumc;
				break;
			}
		}
		long long cst = a[top].num * a[top].val;
		if (top > 0) cst += sum[top - 1];
		ans = max(ans, sumr + cst);
	}
	printf("%lld", ans);
	return 0;
}
原文