题意:
给定 n 个大小 A1,A2,⋯,An 为 2 的整数次幂的数据对象,以及 m 个剩余空间为 B1,B2,⋯,Bm 的分条。问是否可以通过对数据对象进行聚合,使得能用现有的 m 个分条把所有 n 个对象存下来。T 组数据。
知识点:
贪心
题解:
用一个数组储存第一组数据,再使用一个从大到小的优先队列储存空间,根据贪心的思想不断将数组中的最大值存入最大空间,如果能完成一轮遍历就输出Yes,否则输出No。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
priority_queue<LL,vector<LL>,less<LL> > p;
int main () {
// ios::sync_with_stdio(false);
// cin.tie(0);
// cout.tie(0);
LL tt;
cin >> tt;
while (tt -- ) {
LL n, m;
cin >> n >> m;
LL q[n + 1], p1[n + 1];
LL sum1 = 0, sum2 = 0;
bool flag = false;
while (p.empty() == false) {
p.pop();
}
for (int i = 1; i <= n; i ++ ) {
cin >> q[i];
sum1 += q[i];
}
for (int i = 1; i <= m; i ++ ) {
cin >> p1[i];
sum2 += p1[i];
p.push(p1[i]);
}
if (sum1 > sum2) {
cout << "No" << endl;
continue;
}
sort (q + 1, q + n + 1, greater<int>());
for (int i = 1; i <= n; i ++ ) {
LL res = p.top ();
if(res < q[i]) break;
p.push (res - q[i]);
p.pop();
if(i == n) flag = true;
}
// cout << "#########" << endl;
// for (int i = 1; i <= m; i ++ ) cout << p[i] << " ";
// cout << endl;
if (flag == true) {
cout << "Yes" << endl;
}else {
cout << "No" << endl;
}
// cout << "#########" << endl;
}
//system ("pause");
return 0;
}