[Blue Bridge Cup] [algorithm improves VIP] shield of God and Jenga Easy only once * greedy thought, similar to the banker's algorithm

The basic idea:

In a nutshell is greedy, to demand the number of sort, to meet the minimum requirements, to take back some of his original, longer meet the needs of a large number;

In fact, there is a replica of OS banker algorithm;

 

key point:

Note that there are circumstances case Forty-five percent greater than the number to have the number of full demand, the need to look at;

 

#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;
}

  

Guess you like

Origin www.cnblogs.com/songlinxuan/p/12353181.html