思路
把所有的飞船攻击力和编号封装起来,再把每一个基地的攻击力和黄金量封装,把飞船和基地按攻击力排序,之后就是对于每一个飞船能攻击的基地从小到大遍历,只不过可以把前一个飞船的遍历到的位置和能拿到的黄金数给存起来,这样下一个飞船就不用再从头遍历,只要从存下来的地方去遍历就可以了。
代码
#include<cstdio>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
#define ll long long
const int maxn = 1e5;
struct base {
ll att;
ll gold;
bool operator < (const base& b) {
return att < b.att;
}
};
struct spaceship {
ll att;
int number;
bool operator < (const spaceship& b) {
return att < b.att;
}
};
spaceship a[maxn];
base b[maxn];
ll ans[maxn];//存下最后的每一个飞船的黄金
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
scanf_s("%d", &a[i].att);
a[i].number = i;
}
for (int i = 0; i < m; i++) {
scanf_s("%d%d", &b[i].att, &b[i].gold);
}
sort(a, a + n);
sort(b, b + m);
int idx = 0;//来存当前遍历到的基地位置
ll allgold = 0;//存下上一次的黄金数
for (int i = 0; i < n; i++) {
int j = idx;
ll sum = allgold;
while (j < m&&b[j].att <= a[i].att) {
sum += b[j].gold;
j++;
}
ans[a[i].number] = sum;
idx = j;
allgold = sum;
}
for (int i = 0; i < n; i++) {
cout << ans[i] << " ";
}
}