[Cometoj#3 A]比赛_枚举/堆 比赛

题目链接https://cometoj.com/contest/38/problem/A?problem_id=1534

数据范围:略。


题解

原题没啥意思,就是个暴力枚举。

出了个加强版,$1le n,kle 10^5$。

因为$k$只有$10^5$,所以我们可以以此求出来前$k$个。

直接用堆贪心以下即可。

代码

#include <bits/stdc++.h>

#define N 1000010 

using namespace std;

typedef long long ll;

char *p1, *p2, buf[100000];

#define nc() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1 ++ )

int rd() {
	int x = 0;
	char c = nc();
	while (c < 48) {
		c = nc();
	}
	while (c > 47) {
		x = (((x << 2) + x) << 1) + (c ^ 48), c = nc();
	}
	return x;
}

priority_queue <pair<int, pair<int, int> > >q;

int a[N];

int main() {
	int n = rd(), k = rd();
	for (int i = 1; i <= n; i ++ ) {
		a[i] = rd();
	}
	sort(a + 1, a + n + 1);
	for (int i = 1; i < n; i ++ ) {
		q.push(make_pair(a[i] + a[i + 1], make_pair(i, i + 1)));
	}
	ll ans = 0;
	for (int i = 1; i <= k; i ++ ) {
		int x = q.top().second.first, y = q.top().second.second;
		ans += a[x] + a[y];
		q.pop();
		if (x > 1) {
			q.push(make_pair(a[x - 1] + a[y], make_pair(x - 1, y)));
		}
	}
	cout << ans << endl ; 
	return 0;
}