跳到正文

题解

题解:P11960 [GESP202503 五级] 平均分配

YCX2012约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年3月23日
收录
2026年4月15日
更新
2026年11月17日
篇幅
约 3 分钟
题目
P11960

版本

  1. v1当前

P11960 [GESP202503 五级] 平均分配(题目传送门)

易错点:

  1. 答案变量 int 存不下,要开 long long
  2. 写读入和遍历时,循环次数要是 2*n(我就忘乘了,卡了 5 分钟)
  3. 每个人只能买 n 个

AC代码:

C++
#include<bits/stdc++.h> //万能头
using namespace std;
struct things {
	int b, c, more_money; //用结构体存小B的钱,小A的钱和多多少;
};
bool cmp(things x, things y) { //结构体排序,把差更大的排前面
	return x.more_money > y.more_money;
}
int n;
things a[200005];
long long ans;
int main() {
	cin >> n;
	for (int i = 1; i <= 2 * n; i++)
		cin >> a[i].b; //读入小B
	for (int i = 1; i <= 2 * n; i++) {
		cin >> a[i].c; //读入小C
		if (a[i].b > a[i].c) { //如果小B钱多
			a[i].more_money = a[i].b - a[i].c;
		} else if (a[i].c > a[i].b) { //如果小C钱多
			a[i].more_money = a[i].c - a[i].b;
		} else { //一样多
			a[i].more_money = a[i].c - a[i].b;
		}
	}
	sort(a + 1, a + 2 * n + 1, cmp); //差距越大赚的越多,放在前面先算
	int b_n = 0, c_n = 0; //一人只能拿N个物品(记录次数)
	for (int i = 1; i <= 2 * n; i++) { //统计
		if (a[i].b > a[i].c) { //如果小B出钱多
			if (b_n < n) { //只有小B没买到n个才能继续买
				ans += a[i].b;
				b_n++;
			} else { //小B已经买了n个了,只能小C买
				ans += a[i].c;
				c_n++;
			}
		} else if (a[i].c > a[i].b) { //如果小C出钱多
			if (c_n < n) { //只有小C没买到n个才能继续买
				ans += a[i].c;
				c_n++;
			} else { //小C已经买了n个了,只能小B买
				ans += a[i].b;
				b_n++;
			}
		} else { //一样多(因为差最小所以到最后了,加就完了)
			ans += a[i].b;
		}
	}
	cout << ans; //输出
	return 0;
}

AC记录

原文