题目:https://www.luogu.org/problemnew/show/P1631
题解
方法一:将所有情况视为n*n的二维表格,然后贪心+堆排序
#include<cstdio>
#include<queue>
using namespace std;
int a[100005]={}, b[100005]={}, to[100005]={},i, n;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > >q;
int main()
{
scanf("%d", &n);
for (i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (i = 1; i <= n; i++)
{
scanf("%d", &b[i]); to[i] = 1;
q.push(pair<int, int>(a[1] + b[i], i));
}
while (n--)
{
printf("%d ", q.top().first);
i = q.top().second; q.pop();
q.push(pair<int, int>(a[++to[i]] + b[i], i));
}
return 0;
}
方法二:
#include<queue>
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100005;
struct data{
int x, y, v;
bool operator <(const data &y) const{
return v > y.v;//小根堆
}
};
int n, a[N], b[N], X[N], Y[N];
priority_queue<data> pq;
//在结构体中重定义小于号,维护一个小根堆
int read()
{
int x = 0;
bool f = 0;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-') f = 1;
ch = getchar();
}
while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ '0'), ch =getchar();
return !f ? x : -x;
}
//优雅的读入优化
int main()
{
scanf("%d",&n);
data x, y, k;
int tot = n;
for(int i = 1; i <= n; i++) scanf("%d",&a[i]);
for(int i = 1; i <= n; i++) scanf("%d",&b[i]);
sort(a + 1, a + n + 1);
sort(b + 1, b + n + 1);
for(int i = 1; i <= n; i++) k.x = k.y = i, k.v = a[i] + b[i], pq.push(k);//初始化压入
for(int i = 1; i <= n; i++)
{
k = pq.top(); pq.pop();
printf("%d ", k.v);
if(k.x == k.y)
{
x.x = k.x; x.y = k.y + 1; x.v = a[x.x] + b[x.y]; pq.push(x);
y.x = k.x + 1; y.y = k.y; y.v = a[y.x] + b[y.y]; pq.push(y);
}
else
{
//为什么 i<j 时不压入 a[i+1]+b[j] ?
//我们考虑到此时 a[i+1]+ b[j-1] 及之前的数字可能依旧在优先队列中并且更优,就不必更新。
if(k.x > k.y) y.x = k.x + 1, y.y = k.y, y.v = a[y.x] + b[y.y], pq.push(y);
else x.x = k.x, x.y = k.y + 1, x.v = a[x.x] + b[x.y], pq.push(x);
}
}
return 0;
}