杭州网络赛的题,可以假设杀掉一个敌人后,剑落在地上,以后还可以捡起来,这样问题就可以简化不少。
/**
贪心题,俩种方式,一种优先考虑bi不为0的情况,因为这样可以造成不消耗耐久连续杀人;
一种优先考虑,bi为0的情况,比如特殊数据:
input:
5 8
1 0
2 0
2 0
3 0
6 1
output:
4 8
3 7 或 3 8(为错误答案)
只考虑bi为0的个体,比先考虑bi不为0的情况,杀的人要多。
俩种方案最后比较取出最有解。
**/
#include <stdio.h>
#include <stdlib.h>
struct Creed
{
int ai, bi;
} CR[100002];
int cmp2(const void *a, const void *b)
{
Creed *aa = (Creed*)a;
Creed *bb = (Creed*)b;
if(aa->ai != bb->ai)
return aa->ai - bb->ai;
return aa->bi - bb->bi;
}
int main()
{
int t, m ,n, mm, ff;
int i, cct = 0, tot1, tot2, num1, num2;
scanf("%d", &t);
while(t--)
{
tot1 = num1 = num2 = 0;
int sum_bi = 0;
printf("Case %d: ", ++cct);
scanf("%d%d", &n, &m);
for(i = 0; i < n; i++)
scanf("%d%d", &CR[i].ai, &CR[i].bi);
qsort(CR, n, sizeof(CR[0]), cmp2); // 按ai增序排列,ai值相同的按bi值增序排列
mm = m;
for(i = 0; i < n; i++) // (考虑)杀的所有个体全是bi为0的情况,则m依次从最小的ai值开时减,直到不能减为止
if(mm >= CR[i].ai)
{
++num1;
mm -= CR[i].ai;
tot1 += CR[i].ai;
}
for(i = 0; i < n; i++) // 找出第一个bi值不为0的个体
if(CR[i].bi)
break;
if(i != n) // bi值不全为0时考虑第二种方案,全为0时,不必考虑第二种方案
if(CR[i].ai <= m) // bi值不为0的最小ai值都大于m,则一个人都杀不了或只能杀bi为0的个体,第二种方案则不用考虑
{
tot2 = CR[i].ai;
m -= CR[i].ai;
ff = i; // 用来标识第一个要杀的人
for(int j = 0; j < n; j++)
sum_bi += CR[j].bi; // 统计bi的总值
if(sum_bi >= n) // bi总值大于n,则n个人一定可以全部杀掉
{
printf("%d %d\n", n, tot2);
continue;
}
num2 = sum_bi + 1;
int nn = n - sum_bi - 1; // sum_bi杀完ai值最大的那一部分,剩下那部分用自己的剑去杀
for(i = 0; i < nn; i++) // 杀到m值不能再杀为止
if(m >= CR[i].ai && ff != i) // ff != i 排除掉第一个杀的人
{
++num2;
m -= CR[i].ai;
tot2 += CR[i].ai;
}
else if(ff == i)
++nn;
}
if(num2 > num1) // 比较两种方式哪种杀的人最多
printf("%d %d\n", num2, tot2);
else if(num2 == num1 && tot2 < tot1) //杀的人一样的条件下,哪种消耗的耐久最少
printf("%d %d\n", num2, tot2);
else
printf("%d %d\n", num1, tot1);
}
return 0;
}
附(比赛时测试的数据):
Input:
10
4 4
2 1
2 1
3 0
3 0
5 8
1 0
2 0
2 0
3 0
6 1
5 5
4 0
5 0
2 1
3 2
3 2
7 5
2 0
3 0
4 0
5 0
2 1
3 2
3 2
5 5
2 0
3 0
4 0
2 1
3 2
3 5
4 1
5 1
7 7
2 1
2 2
4 0
4 4
2 0
2 0
1 0
1 0
3 10
10 1
12 0
13 0
4 10
10 1
2 0
2 0
2 0
Output:
Case 1: 4 4
Case 2: 4 8
Case 3: 5 2
Case 4: 7 4
Case 5: 5 4
Case 6: 3 4
Case 7: 0 0
Case 8: 3 4
Case 9: 2 10
Case 10: 3 6