贪心算法典型——Monster(HDU - 3979)
定义
贪心算法是指,在对问题求解时,总是做出在当前看来是最好的选择。
也就是说,不从整体最优上加以考虑,他所做出的仅是在某种意义上的局部最优解。
题解
One day, v11 encounters a group of monsters in a foreast. In order to defend the homeland, V11 picks up his weapon and fights!
All the monsters attack v11 at the same time. Every enemy has its HP, and attack value ATK. In this problem, v11 has his ATK and infinite HP. The damage (also means reduction for HP) is exactly the ATK the attacker has. For example, if v11’s ATK is 13 and the monster’s HP is 27, then after v11’s attack, the monster’s HP become 27 - 13 = 14 and vice versa.
v11 and the monsters attack each other at the same time and they could only attack one time per second. When the monster’s HP is less or equal to 0 , we think this monster was killed, and obviously it would not attack any more. For example, v11’s ATK is 10 and a monster’s HP is 5, v11 attacks and then the monster is killed! However, a monster whose HP is 15 will be killed after v11 attack for two times. v11 will never stop until all the monsters are killed ! He wants to minimum the HP reduction for the fight! Please note that if in some second, some monster will soon be killed , the monster’s attack will works too.
Input
The first line is one integer T indicates the number of the test cases. (T <=100)
Then for each case, The first line have two integers n (0<n<=10000), m (0<m<=100), indicates the number of the monsters and v11’s ATK . The next n lines, each line has two integers hp (0<hp<=20), g(0<g<=1000) ,indicates the monster’s HP and ATK.
Output
Output one line.
First output “Case #idx: ”, here idx is the case number count from 1. Then output the minimum HP reduction for v11 if he arrange his attack order optimal .
Sample Input
2
3 1
1 10
1 20
1 40
1 10
7 3
Sample Output
Case #1: 110
Case #2: 3
题意大致如下:v11面对多个怪兽,以什么顺序击杀怪兽会使v11的耗血最少。在v11,对其中一个怪兽攻击时,所有怪兽会对v11攻击。
举个例子假如有两个怪兽A和B,A怪兽的血量为HPA,攻击力为SA,B怪兽的血量为HPB,攻击力为SB,v11的攻击力为m,现在有两种方法,一:先击杀A后击杀B。二:先击杀B后击杀A。一耗血量:(HPA/m)*(SA+SB)+(HPB/m)*SB.同理二耗血量为:(HPB/m)*(SA+SB)+(HPA/m)*SA。接下来就是比较两种方法哪一种耗血比较少了。即比较HPA*SB与HPB*SA的大小所以这就找到了局部贪心的标准。
下面是ac的代码
特别注意要开long long
#include <iostream>
#include <algorithm>
#include<cmath>
using namespace std;
struct ac{
long long hp,g;
long long c;
}s[10050];
long long n,m;
long long ca=0;
bool cmp(const ac &a,const ac &b)
{
return a.hp*b.g<a.g*b.hp;}
void solve(){
scanf("%lld %lld",&n,&m);
long long k=0,sum=0,ss=0;
for(int i=0;i<n;i++)
{
scanf("%lld %lld",&s[i].hp,&s[i].g);
s[i].hp=(long long)ceil((double)s[i].hp/(double)m);
sum+=(long long)(s[i].g);
}
sort(s,s+n,cmp);
for(int i=0;i<n;i++){
ss+=(long long)(sum*s[i].hp);
sum-=(long long)(s[i].g);
}
printf("Case #%lld: %lld\n",++ca,ss);
}
int main(){
int t;
scanf("%d",&t);
while(t--){
solve();
}
return 0;
}
本文来自博客园,作者:{HB_B},转载请注明原文链接:https://www.cnblogs.com/SJNNN/p/15635379.html

浙公网安备 33010602011771号