Codeforces-Smilo and Monsters

文章讲述了如何通过排序怪兽血量并利用连击器策略,最小化杀戮所有怪兽所需的攻击次数,C++代码展示了优化的解决方案。
摘要由CSDN通过智能技术生成

题意

n个成群的怪兽,每群分别有 xi个怪兽,有两种攻击方式:1.每次攻击一个群中的一个怪兽一滴血,然后连击器加1; 2. 使用连击器攻击一次造成连击器的伤害,然后连击器重置为0; 问最少杀完所有怪物的攻击次数

题解

攻击次数最少,就要使得每次攻击的利益最大化。即每次攒起来的连击数都要击杀最多血量的怪兽。所以可以先对输入的怪兽进行排序,从前累计计数器,若能刚好杀死最多血量的,则直接杀死;若大于最大血量的,为了利益最大化,只计数到刚好杀死这个怪物即可。最后要对最后一只怪物特殊处理一下节约时间。

#include<iostream>
#include<algorithm>
using namespace std;
const int N = 2e5 + 5;
#define int long long
int t, n;
int a[N];
int cnt; // 计数器
int res;
void init() {
	cnt = 0;
	res = 0;
}
signed main() {
	std::ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> t;
	while (t--) {
		init(); // 每个样例都初始化
		cin >> n;
		for (int i = 1; i <= n; ++i) cin >> a[i];
		sort(a + 1, a + 1 + n);
		int i, j;
		for ( i = 1, j = n;  i < j; ) {
			// 1.如果血量最少的够杀领主
			if (cnt + a[i] >= a[j] ) {
				res += a[j] - cnt + 1;	a[i] -= a[j] - cnt;	cnt = 0;	a[j] = 0;	j--;
			}
			// 血量不够击杀领主
			else {
				res += a[i];	cnt += a[i];	a[i] = 0;	i++;
			}
		}  // 1 1 1 2
		//  1 1   0
		//   cout <<"1213          " << i <<endl;
		while(a[i] > 0 ) {
			// 剩余的快速处理
            int s = (a[i] - cnt) >> 1; // 剩余的血量
            res += s;    a[i] -= s; cnt += s;
            if(cnt){ // 多一个使用连击器
                res++;    a[i] -= cnt;    cnt = 0;
            }
            if(a[i]){
                a[i]--;    res++;
            }
		}
        // cout << a[i] << endl;
		cout << res << endl;
	}
	return 0;
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值