CSU-暑假集训题 Superhero Battle
题目链接:http://codeforces.com/problemset/problem/1141/E
题目
A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly n
minutes. After a round ends, the next round starts immediately. This is repeated over and over again.
Each round has the same scenario. It is described by a sequence of n
numbers: d1,d2,…,dn (−106≤di≤106). The i-th element means that monster's hp (hit points) changes by the value di during the i-th minute of each round. Formally, if before the i-th minute of a round the monster's hp is h, then after the i-th minute it changes to h:=h+di
.
The monster's initial hp is H
. It means that before the battle the monster has H hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 0
. Print -1 if the battle continues infinitely.
Input
The first line contains two integers H
and n (1≤H≤1012, 1≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dn (−106≤di≤106), where di is the value to change monster's hp in the i
-th minute of a round.
Output
Print -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer k
such that k
is the first minute after which the monster is dead.
Examples
1000 6 -100 -200 -300 125 77 -4
9
1000000000000 5 -1 0 0 0 0
4999999999996
10 4 -3 -6 5 4
-1
思路
其实就是个数学题,就是计算第几次攻击后hp变成0,对于每一轮(行)攻击,可能减少最多并不是在最后,所以要计算出最后一轮是第几轮。
数组a[i]中存储的是每一轮中到第i次攻击改变(可能为正可能为负)的hp,用minn记录一轮中的最小值,最后一轮就是(h+minn)/a[n]+1,若(h+minn)%a[n]为0,则减一。
AC代码
#include<iostream> using namespace std; long long h; long long a[200020],b[200020],ans=0; int main(){ int n; cin>>h>>n; long long minn=h; for(int i=1;i<=n;i++){ cin>>a[i]; a[i]+=a[i-1]; if(a[i]<minn)minn=a[i]; } if(h+minn>0&&a[n]>=0){ //如果在第一轮不能被减完而且一轮下来是增加的,就无解 cout<<-1<<endl; return 0; } if(h+minn>0) { long long beishu=(h+minn)/(-a[n])+1; //求出的倍数是大于等于那个倍数的整数,所以要加1 n>=(h+min)/a[i] if((-a[n])*(beishu-1)-minn==h){ //如果(h+min)/a[i]正好整除,则反过来算正好能求得h,就要减1 beishu--; } ans+=beishu*n; h=h-((-a[n])*beishu); } for(int i=1;i<=n;i++) { if((-a[i])<h)continue; else { ans+=i; break; } } cout<<ans<<endl; return 0; }

浙公网安备 33010602011771号