简单典型贪心---(解题报告)HDU4310---Hero

来源:互联网 发布:linux根目录介绍 编辑:程序博客网 时间:2024/05/23 22:59

Hero

Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3379 Accepted Submission(s): 1516

Problem Description
When playing DotA with god-like rivals and pig-like team members, you have to face an embarrassing situation: All your teammates are killed, and you have to fight 1vN.

There are two key attributes for the heroes in the game, health point (HP) and damage per shot (DPS). Your hero has almost infinite HP, but only 1 DPS.

To simplify the problem, we assume the game is turn-based, but not real-time. In each round, you can choose one enemy hero to attack, and his HP will decrease by 1. While at the same time, all the lived enemy heroes will attack you, and your HP will decrease by the sum of their DPS. If one hero’s HP fall equal to (or below) zero, he will die after this round, and cannot attack you in the following rounds.

Although your hero is undefeated, you want to choose best strategy to kill all the enemy heroes with minimum HP loss.

Input
The first line of each test case contains the number of enemy heroes N (1 <= N <= 20). Then N lines followed, each contains two integers DPSi and HPi, which are the DPS and HP for each hero. (1 <= DPSi, HPi <= 1000)

Output
Output one line for each test, indicates the minimum HP loss.

Sample Input
1
10 2
2
100 1
1 100

Sample Output
20
201

解题思路:
1.首先是这个题的题目意思,讲的是在你打游戏时面对了以一打多的情况,这时你开了无敌状态,有无限的生命,但是你的攻击力变为了1,试问你把所有敌人打倒时你消耗的最少生命值;
2.很容易看出这是个最简单的贪心问题,贪心思想的体现:将DFS与HP的比值进行从大到小的排序,然后按这个顺序依次打。
3. 这里我有一点分析,当排好序后,怎么很快的写出打怪时的代码,我觉得应该首先分析的是那些量在打的时候是变化的,然后找出这些变化的量之间的联系,分析出代码,在这个题中变化的是受到伤害的总数(即你最后要输出的数),然后是剩下总的人数(这里主要体现在每打一个人之后剩下的攻击力也即你下一轮会受到的伤害),这样很轻松就可以想出代码;

代码如下:

#include <iostream>#include <cstring>#include <algorithm>using namespace std;typedef struct data{    double DFS;    double HP;    double comp;}data;int cmp(data x,data y){                 return x.comp>y.comp;}int main(){    int n;    data a[50];    while(cin>>n&&n)    {        int i,sum=0,        allDFS=0,        afterDFS=0;        memset(a,0,sizeof(a));        for(i=0;i<n;i++)        {            cin>>a[i].DFS>>a[i].HP;            a[i].comp=a[i].DFS/a[i].HP;       //贪心思想的体现:将DFS与HP的比值进行从大到小的排序,然后按这个顺序依次打。             allDFS+=a[i].DFS;        }        sort(a,a+n,cmp);         for(i=0;i<n;i++)                //打怪时的代码,注意是一个敌人一个敌人的打,关键是分析在打的过程中那些量是变化的,然后找出其联系,就可以很顺的写出代码了。         {            sum+=(allDFS-afterDFS)*a[i].HP;    //此时变化的是受到伤害的总数;               afterDFS+=a[i].DFS;    //这里变化的是死去英雄的攻击力;用总的攻击力减去死去英雄的攻击力的和就是打下一个英雄时受到的单次攻击力;         }        cout<<sum<<endl;    }    return 0;}

仅代表个人观点,不喜勿喷,欢迎交流!!!
这里写图片描述

0 0