洛谷 B4452:[GESP202512 四级] 优先购买 ← 结构体排序
【题目来源】https://www.luogu.com.cn/problem/B4452【题目描述】小 A 有 M 元预算。商店有 N 个商品每个商品有商品名 S、价格 P 和优先级 V 三种属性其中 V 为正整数且V 越小代表商品的优先级越高。小 A 的购物策略为1总是优先买优先级最高的东西2如果有多个最高优先级商品购买价格最低的3如果有多个优先级最高且价格最低的商品购买商品名字典序最小的。小 A 想知道能购买哪些商品。【输入格式】第一行两个正整数 MN代表预算和商品数。之后 N 行每行一个商品依次为 Si Pi Vi代表第 i 个商品的商品名、价格、优先级。数据保证不存在两个名字相同的商品。【输出格式】按照字典序从小到大的顺序输出所有购买商品的商品名。【输入样例】20 4apple 6 8bus 15 1cab 1 10water 4 8【输出样例】buscabwater【数据范围】对于所有测试点保证 1≤∣Si∣≤101≤M,Pi≤10^51≤N≤10^31≤Vi≤10。商品名仅由小写字母组成且不存在两个相同的商品名。【算法分析】● 按结构体某一字段对结构体数组进行排序https://blog.csdn.net/hnjzsyjyj/article/details/120184972● 本题需进行两次排序。【算法代码一string】#include bits/stdc.h using namespace std; const int maxn1e35; struct Goods { string s; int p; int v; } t[maxn]; bool cmp(Goods x,Goods y) { if(x.v!y.v) return x.vy.v; else if(x.p!y.p) return x.py.p; else return x.sy.s; } int main() { int m,n; cinmn; for(int i1; in; i) { cint[i].st[i].pt[i].v; } sort(t1,t1n,cmp); string v[maxn]; int cnt0; for(int i1; in; i) { if(mt[i].p) { m-t[i].p; v[cnt]t[i].s; } } sort(v1,v1cnt); for(int i1; icnt; i) { coutv[i]endl; } return 0; } /* in: 20 4 apple 6 8 bus 15 1 cab 1 10 water 4 8 out: bus cab water */【算法代码二vector】#include bits/stdc.h using namespace std; const int maxn1e35; struct Goods { string s; int p; int v; } t[maxn]; bool cmp(Goods x,Goods y) { if(x.v!y.v) return x.vy.v; else if(x.p!y.p) return x.py.p; else return x.sy.s; } int main() { int m,n; cinmn; for(int i1; in; i) { cint[i].st[i].pt[i].v; } sort(t1,t1n,cmp); vectorstring v; for(int i1; in; i) { if(mt[i].p) { m-t[i].p; v.push_back(t[i].s); } } sort(v.begin(),v.end()); for(auto x:v) coutxendl; return 0; } /* in: 20 4 apple 6 8 bus 15 1 cab 1 10 water 4 8 out: bus cab water */【参考文献】https://mp.weixin.qq.com/s/sWxpISqwh2OfFGjqVIn1PQhttps://blog.csdn.net/jht0105/article/details/135998672https://blog.csdn.net/m0_69389639/article/details/146261239