Circle of Monsters【贪心】

题目描述:原题链接

You are playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has ai health.

You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by 1 (deals 1 damage to it). Furthermore, when the health of some monster i becomes 0 or less than 0, it dies and explodes, dealing bi damage to the next monster (monster i+1, if i<n, or monster 1, if i=n). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.

You have to calculate the minimum number of bullets you have to fire to kill all n monsters in the circle.

Input
The first line contains one integer T (1≤T≤150000) — the number of test cases.

Then the test cases follow, each test case begins with a line containing one integer n (2≤n≤300000) — the number of monsters. Then n lines follow, each containing two integers ai and bi (1≤ai,bi≤1012) — the parameters of the i-th monster in the circle.

It is guaranteed that the total number of monsters in all test cases does not exceed 300000.

Output
For each test case, print one integer — the minimum number of bullets you have to fire to kill all of the monsters.

Example
input
1
3
7 15
2 14
5 3
output
6

思路:

先算出如果引爆所有怪兽,剩下的还需要补枪数的和sum。之后只需要选出消耗最小的,成为第一只引爆的怪兽。就是求sum-max(ai-b(i-1),0)+ai 的最小值。也就是求每一个补枪数和每一个a中的最小值。因为每一个超出的血量都已经加到sum中了,所以可能某一个补枪数要小于所有的a。

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=300010;
 
int t, n;
ll minn, sum, k, a[N], b[N];

int main()
{
	scanf("%d",&t);
	while (t--)
	{
		scanf("%d",&n);
		sum = 0;
		for (int i = 0; i < n; i++)
		{
			scanf("%lld %lld",&a[i],&b[i]);
			if (i && a[i] > b[i - 1]) sum += a[i] - b[i - 1];
		}
		if (a[0] > b[n - 1]) sum += a[0] - b[n - 1], minn = b[n - 1];
		else minn = a[0];
		for (int i = 1; i < n; i++)
		{
			if (a[i] > b[i - 1]) k = b[i - 1];
			else k = a[i];
			minn = min(k,minn);
		}
		printf("%lld\n",minn+sum);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值