题解:洛谷 AT_abc461_c [ABC461C] Variety
本文分享的必刷题目是从蓝桥云课、洛谷、AcWing等知名刷题平台精心挑选而来并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。欢迎大家订阅我的专栏算法题解C与Python实现附上汇总贴算法竞赛备考冲刺必刷题C | 汇总【题目来源】洛谷AT_abc461_c [ABC461C] Variety - 洛谷【题目描述】There areN NNgems. The color (represented as an integer) of thei ii-th gem isC i C_iCiand its value isV i V_iVi.ChooseK KKgems from theseN NNgems. Here, the chosen gems must have at leastM MMdistinct colors.Find the maximum possible total value of the chosen gems. (Such a choice is always possible in the given input.)有N NN颗宝石。第i ii颗宝石的颜色用整数表示是C i C_iCi价值是V i V_iVi。从这N NN颗宝石中选择K KK颗。此处被选中的宝石必须具有至少M MM种不同的颜色。求所选宝石的最大可能总价值。在给定输入中这样的选择总是可行的。【输入】The input is given from Standard Input in the following format:N NNK KKM MMC 1 C_1C1V 1 V_1V1C 2 C_2C2V 2 V_2V2⋮ \vdots⋮C N C_NCNV N V_NVN【输出】Output the maximum possible total value of the chosen gems as an integer.【输入样例】5 3 2 1 30 1 40 1 50 2 10 3 20【输出样例】110【算法标签】#普及- #贪心【代码详解】#includebits/stdc.husingnamespacestd;#defineintlonglongconstintN200005;// 定义最大数量intn,k,m,ans;// 物品数n总选择数k颜色数m总价值ansstructNode{intc,v;// 颜色c价值vboolflag;// 是否被选择}a[N];boolcolor[N];// 颜色是否被使用boolcmp(Node x,Node y)// 排序比较函数{returnx.vy.v;// 按价值从大到小排序}signedmain()// 主函数{cinnkm;// 输入物品数、总选择数、颜色数for(inti1;in;i)// 读取所有物品{cina[i].ca[i].v;// 输入颜色和价值a[i].flagfalse;// 初始化未选择}sort(a1,an1,cmp);// 按价值排序intcnt0;// 已选择物品计数for(inti1;in;i)// 第一轮每个颜色至少选一个{if(cntm)break;// 已选够m个颜色if(!color[a[i].c])// 如果这个颜色还没被选过{color[a[i].c]true;// 标记颜色被使用a[i].flagtrue;// 标记物品被选择ansa[i].v;// 累加价值cnt;// 计数增加}else// 如果颜色已被选过continue;// 跳过}for(inti1;in;i)// 第二轮选满k个物品{if(cntk)break;// 已选够k个物品if(!a[i].flag)// 如果物品还未被选择{a[i].flagtrue;// 标记物品被选择ansa[i].v;// 累加价值cnt;// 计数增加}else// 如果物品已被选择continue;// 跳过}coutansendl;// 输出总价值return0;// 程序正常结束}【运行结果】5 3 2 1 30 1 40 1 50 2 10 3 20 110