[蓝桥杯][算法提高VIP]盾神与积木游戏 Easy only once *贪心思想,类似于银行家算法
基本思想:
简而言之就是贪心,对需求数进行排序,先满足最小需求,把他原先有的拿回来,再满足需求数目大的;
其实就是OS里银行家算法的翻版;
关键点:
注意有百分之四十五的case情况为拥有数目完全大于需求数目,这个需要注意一下;
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector>
#include<string>
#include<math.h>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
#include<set>
#include<stack>
using namespace std;
struct node {
int xuyao;
int yiyou;
};
vector<node>vec;
vector<string>res;
int m, n;
bool cmp(node a, node b) {
return a.xuyao < b.xuyao;
}
int main() {
cin >> m;
int a, b;
for (int i = 0; i < m; i++) {
vec.resize(0);
cin >> n;
int cnt=0;
bool flag=true;
for (int i = 0; i < n; i++) {
cin >> a >> b;
if (a >= b) {
cnt += a;
}
else {
node no;
no.xuyao = b - a;
no.yiyou = a;
vec.push_back(no);
}
}
sort(vec.begin(), vec.end(),cmp);
for (int i = 0; i < vec.size(); i++) {
if (vec[i].xuyao<=cnt) {
//如果可以分配;
cnt += vec[i].yiyou;
}
else {
//如果不可以分配;
flag = false;
break;
}
}
if (flag)
res.push_back("YES");
else
res.push_back("NO");
}
for (auto ele : res) {
cout << ele << endl;
}
return 0;
}

浙公网安备 33010602011771号