手最快的一集
定义结构体: 首先定义了一个Card结构体,用于存储卡片的类型(type)以及所需的三种资源数量(r, g, b)。
输入处理: 程序从标准输入读取卡片数量n,然后读取每张卡片的类型和所需资源数量,并存储在cards向量中。
排序: 使用sort函数对卡片进行排序,排序依据是卡片所需总资源数量(r + g + b)的升序。这样做的目的是为了先尝试购买资源需求较低的卡片。
购买逻辑: 初始化三种资源的数量(R, G, B)和已购买卡片计数(count)。使用一个循环尝试购买卡片,如果当前资源允许购买某张卡片,则增加相应资源的数量,并将卡片类型标记为0(表示已购买)。循环直到没有卡片可以购买为止。
输出结果: 最后输出已购买的卡片数量。
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
using ll = long long;
using ull = unsigned long long;
// 定义卡片结构体,包含类型和所需三种资源数量
struct Card
{
char type;
int r, g, b;
};
// 判断是否可以购买某张卡片
bool canBuy(const Card &card, int R, int G, int B)
{
return R >= card.r && G >= card.g && B >= card.b;
}
signed main()
{
int n;
cin >> n; // 读取卡片数量
vector<Card> cards(n);
for (int i = 0; i < n; i++)
{
cin >> cards[i].type >> cards[i].r >> cards[i].g >> cards[i].b; // 读取每张卡片的类型和所需资源数量
}
// 根据卡片所需总资源数量进行排序
sort(cards.begin(), cards.end(), [](const Card &a, const Card &b)
{ return a.r + a.g + a.b < b.r + b.g + b.b; });
int R = 0, G = 0, B = 0, count = 0; // 初始化资源数量和已购买卡片计数
bool bought;
// 尝试购买卡片,直到没有卡片可以购买
do
{
bought = false;
for (int i = 0; i < n; i++)
{
if (!cards[i].type) // 如果卡片已购买,跳过
continue;
if (canBuy(cards[i], R, G, B)) // 如果可以购买卡片
{
count++; // 增加已购买卡片计数
bought = true; // 标记为已购买
if (cards[i].type == 'R')
R++; // 增加红色资源数量
if (cards[i].type == 'G')
G++; // 增加绿色资源数量
if (cards[i].type == 'B')
B++; // 增加蓝色资源数量
cards[i].type = 0; // 标记卡片为已购买
}
}
} while (bought); // 如果本次循环没有购买任何卡片,结束循环
cout << count << endl; // 输出已购买的卡片数量
}