UVALive 7146 Defeat the Enemy (贪心)
来源:互联网 发布:mac怎么换u盘格式 编辑:程序博客网 时间:2024/05/16 14:48
题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=5158
题面:
题目大意:
敌我双方,我方n只军队,敌方m只军队,每只军队两个属性值,生命值和攻击力。两军交战,本身生命值减去对方的攻击力。若剩余生命值小于等于0,则牺牲。问我军能否消灭敌军,能的话,最多生还多少队伍,不能的话,输出-1。
解题:
做的时候,怎么都理不清思路,因为要结合数据结构考虑,始终觉得无法找到合适的数据结构。参考了这篇博客,大致思路是这样的,首要任务是消灭全部敌军,次要任务是保全更多的自己的部队。先将我方军队按攻击力排序,敌方军队按生命值排序。用multiset维护我方军队的生命值,只要加入multiset中的军队,其攻击力都是足以消灭敌方的当前和以后的队伍的。对于敌方的一只军队,找到我方中,能消灭他的,且不被他消灭的最小生命值,倘若不存在,则牺牲multiset中最小的那个值。
总结:
对于贪心问题,要明确贪心策略,理清思路,才能有助于解题。
补充:
另外multiset的使用也需小心,erase操作,对应两种参数,如果是一个数值的话,那删除的是所有该数值的值,如果是一个迭代器,那只删除该迭代器对应的值。详见此博客。
代码:
#include <iostream>#include <algorithm>#include <set>#include <cstdio>#include <cstring>using namespace std;struct troop{//伤害,生命值int harm,life;}us[100010],en[100010];//按攻击力排序bool cmp1(troop a,troop b){return a.harm>b.harm;}//按生命值排序bool cmp2(troop a,troop b){return a.life>b.life;}int main(){int t,p=0,cnt,n,m;bool flag;scanf("%d",&t);for(int i=1;i<=t;i++){printf("Case #%d: ",i);scanf("%d%d",&n,&m); for(int j=0;j<n;j++)scanf("%d%d",&us[j].harm,&us[j].life);for(int j=0;j<m;j++)scanf("%d%d",&en[j].harm,&en[j].life);//如果我方军队数量小于敌方,直接输出-1if(n<m){printf("-1\n");continue;}//我方按攻击力高排序sort(us,us+n,cmp1);//敌方按生命值排序sort(en,en+m,cmp2);//存储我方的攻击力multiset <int> defense;//p我方下标,cnt我方牺牲数量p=cnt=0;flag=true; for(int j=0;j<m;j++){for(int k=p;k<n;k++){//把我方能消灭敌方军队的军队的生命值都加入multisetif(us[k].harm>=en[j].life){defense.insert(us[k].life);p++;}else break;}//如果我方剩余军队不能消灭敌方队伍,break,输出-1if(defense.empty()){flag=false;break;}else{ //能不损失军队,则用我方生命值恰好高于敌方的去消灭 //倘若必须损失军队,则损失当前生命值最低的 multiset <int> ::iterator it; it=defense.upper_bound(en[j].harm); if(it!=defense.end()) defense.erase(it); else { defense.erase(defense.begin()); cnt++; }}}if(!flag)printf("-1\n");else printf("%d\n",n-cnt);}return 0;}
0 0
- UVALive 7146 Defeat the Enemy (贪心)
- UVALive 7146 Defeat the Enemy (贪心)
- UVALive 7146Defeat the Enemy贪心
- UVALive 7146 Defeat the Enemy (贪心+STL)
- UVALive-7146 Defeat the Enemy (map+贪心)
- UVALive 7146 Defeat the Enemy(模拟)
- UVALive 7146 Defeat the Enemy
- UVA 7146 Defeat The Enemy (贪心)
- UVALive 7146-贪心&数据结构stl-Defeat the Enemy
- UVA Live 7146 Defeat the Enemy(贪心+set)
- UVA LIVE 7146 Defeat the Enemy
- UVA Live 7146 Defeat the Enemy——STL
- UVA 7146 Defeat The Enemy 2014 ACM-ICPC Asia shanghai Regional Contest
- 2014年上海赛区现场赛 I 题 Defeat the Enemy
- hdu4145 Cover The Enemy(贪心+枚举)
- UVALive - 3507 Keep the Customer Satisfied 贪心
- UVALive 2757Supermarket(贪心)
- UVALive 6834Shopping (贪心)
- jQuery UI基础----7jQuery UI Widgets-Accordion(可折叠的
- centos 6 升级gcc
- C++:set_union is not a member of std;
- LEETCODE-Plus One
- 布局方法
- UVALive 7146 Defeat the Enemy (贪心)
- 数据库常用操作
- java中格式化输出小数的问题归纳
- jQuery UI基础----8jQuery UI Widgets-AutoComplete(自动补全
- python+Eclipse+pydev环境搭建
- 近期目标
- jQuery UI基础----9jQurey UI Widgets-Datepicker(日期选择器
- Socket编程基础之服务端与客户端简单通信
- poj 3566 Building for UN(为联合国而建)