Survive the Hits

Survive the Hits

Hard Python Control Flow 12 views
Explanation Complexity

Problem Statement

You start with L lives. You get q events: HIT x (lose x) or HEAL x (gain x). The moment lives becomes

Input Format

• First line: Two integers L q

• L = initial lives

• q = number of events

• Next q lines: Each line contains an event:

• HIT x (lose x lives)

• HEAL x (gain x lives)

Output Format

• Print two integers separated by space:

• Number of events processed

• Final number of lives

Example

10 4
HIT 3
HEAL 2
HIT 9
HEAL 5
3 0

Constraints

• 1 ≤ q ≤ 10^5

• -10^9 ≤ L, x ≤ 10^9

Concept Explanation

Initial lives = 10

1.HIT 3 → lives = 7

2.HEAL 2 → lives = 9

3.HIT 9 → lives = 0

Since lives become 0 (which is ≤ 0),
stop processing further events.

Events processed = 3
Final lives = 0

Step-by-Step Explanation

1.Read L and q.

2.Initialize count = 0.

3.Loop through each of the q events:

• If event is HIT x, subtract x from L.

• If event is HEAL x, add x to L.

• Increase count by 1.

• If L ≤ 0, break the loop.

4.Print count and L.

Concept Explanation

Initial lives = 10

1.HIT 3 → lives = 7

2.HEAL 2 → lives = 9

3.HIT 9 → lives = 0

Since lives become 0 (which is ≤ 0),
stop processing further events.

Events processed = 3
Final lives = 0

Step-by-Step Explanation

1.Read L and q.

2.Initialize count = 0.

3.Loop through each of the q events:

• If event is HIT x, subtract x from L.

• If event is HEAL x, add x to L.

• Increase count by 1.

• If L ≤ 0, break the loop.

4.Print count and L.

Input / Output Format

Input Format
• First line: Two integers L q

• L = initial lives

• q = number of events

• Next q lines: Each line contains an event:

• HIT x (lose x lives)

• HEAL x (gain x lives)
Output Format
• Print two integers separated by space:

• Number of events processed

• Final number of lives
Constraints
• 1 ≤ q ≤ 10^5

• -10^9 ≤ L, x ≤ 10^9

Examples

Input:
10 4 HIT 3 HEAL 2 HIT 9 HEAL 5
Output:
3 0

Example Solution (Public)

Python
import sysnlines=sys.stdin.read().splitlines()nif len(lines)<2:n  sys.exit(0)nL=int(lines[0].strip())nq=int(lines[1].strip())nlives=Lnprocessed=0nfor i in range(q):n  parts=(lines[2+i] if 2+i<len(lines) else '').split()n  if len(parts)<2:n    continuen  typ=parts[0]n  x=int(parts[1])n  if typ=='HIT':n    lives-=xn  else:n    lives+=xn  processed+=1n  if lives<=0:n    breaknsys.stdout.write(f'{processed} {lives}')

Official Solution Code

import sysnlines=sys.stdin.read().splitlines()nif len(lines)<2:n  sys.exit(0)nL=int(lines[0].strip())nq=int(lines[1].strip())nlives=Lnprocessed=0nfor i in range(q):n  parts=(lines[2+i] if 2+i<len(lines) else '').split()n  if len(parts)<2:n    continuen  typ=parts[0]n  x=int(parts[1])n  if typ=='HIT':n    lives-=xn  else:n    lives+=xn  processed+=1n  if lives<=0:n    breaknsys.stdout.write(f'{processed} {lives}')
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.