| # | Problem | Pass Rate (passed user / total user) |
|---|---|---|
| 15095 | Hunter × Pokémon: Nen Dimensional Warehouse |
|
| 15096 | Money's Battlefield |
|
Description
Hunter × Pokémon: Nen Arena
Cabi is a student at NTHU, who recently has faced some trouble with linear algebra.
This month, Cabi received his first midterm exam for Linear Algebra, and he was upset about getting such a bad score. Even worse, he has to face his second Linear Algebra midterm on 11/23 ._..
To make his mood better, he decided to torture I2P students, Cabi decided to take a break by watching Hunter × Hunter while grinding Pokémon battles.
However, being an I2P TA without empathy, Cabi realized that standard Pokémon battles are way too predictable. "What if Hunters command Pokémon using their own Nen (念)-type brains?" he thought. As Hisoka's (西索) famous Nen-type personality analysis goes:
- Enhancers (強化系) are simple and earnest — they blindly spam their strongest attack without overthinking.
- Emitters (放出系) are impatient and careless — they rush to finish the fight and completely ignore healing.
- Transmuters (變化系) are fickle and deceitful — they constantly switch tactics to trick their opponents.
- Manipulators (操作系) are logical and go at their own pace — they follow a strict mathematical formula for resource efficiency.
- Conjurers (具現化系) are high-strung and overly cautious — they panic the moment they lose even 1 HP and prioritize safe, low-cooldown moves.
- Specialists (特質系) are individualistic with a charismatic leader's aura — they refuse to follow conventional rules, living on the edge before unleashing flashy ultimate moves.
(Note: This is entirely Hisoka's arbitrary prejudice—and now it is your OOP assignment.)
An idea crossed Cabi's mind. As an I2P TA without empathy, he decided to let every I2P student implement this battle simulator for him, he thought that will be a piece of cake for these geniuses.
Now, your task is to help Cabi solve the problem. Write an object-oriented program to simulate a turn-based Pokémon battle commanded by two Hunters.
All arithmetic in this problem uses integer division (//) to avoid floating-point precision issues. Here is how the battle system works:
- Cooldown & Resource Management (
Skill):- Each skill has
max_cd(cooldown turns) andmax_pp(maximum uses). Initially,current_cd = 0andcurrent_pp = max_pp. - At the start of a Hunter's turn, every skill's
current_cddecreases by (clamped at ). - A skill is available if and only if
current_cd == 0andcurrent_pp > 0. - When used,
current_ppdecreases by andcurrent_cdis set tomax_cd.
- Each skill has
- Pokémon Types & Damage Calculation (
Pokemon):- Standard damage formula:
effective_def = (defense // 2) if ignore_def_half else defense, andactual_dmg = max(1, raw_dmg - effective_def). - If no skills are available (
chosen is None), the Pokémon usesstruggle, dealingraw_dmg = max(1, atk // 2)(ignore_def_half=False). PowerPokemon:"Attack":raw_dmg = ((atk + skill.power) * 12) // 10,ignore_def_half=False."Pierce":raw_dmg = atk + skill.power,ignore_def_half=False."Heal": heals self byskill.power.
MysticPokemon:"Attack":raw_dmg = atk + skill.power,ignore_def_half=False."Pierce":raw_dmg = atk + skill.power,ignore_def_half=True."Heal": heals self byskill.power.
TankPokemon:- Overrides
take_damage: reduces incomingraw_dmgby first (mitigated_raw = (raw_dmg * 8) // 10), then applies standard defense calculation. "Attack"or"Pierce":raw_dmg = atk + skill.power,ignore_def_half=False."Heal": heals self by(skill.power * 3) // 2.
- Overrides
- Standard damage formula:
- Hunter Nen Brains (
Hunter):- Each Hunter owns a
Pokemonand tracks personal action turns (turn_count, incremented by at the start oftake_turn). - If
available_skillsis empty, all Hunters returnNone. EnhancerHunter: Filters for offensive skills (skill_type in ("Attack", "Pierce")); if none exist, considers allavailable_skills. Picks the one with the highestpower(tie-breaker: smaller skill index).EmitterHunter: Ifenemy_pokemon.defense >= 15and at least one"Pierce"skill is available, picks the"Pierce"skill with the highestpower(tie-breaker: smaller skill index). Otherwise, behaves likeEnhancerHunter.TransmuterHunter: On odd personal turns (turn_count % 2 == 1), picks the available skill with the lowestpower(tie-breaker: larger skill index). On even personal turns (turn_count % 2 == 0), picks the available skill with the highestcurrent_pp(tie-breaker: smallermax_cd, then smaller skill index).ManipulatorHunter: Ifpokemon.hp < pokemon.max_hp // 2and at least one"Heal"skill is available, picks the"Heal"skill with the highestpower(tie-breaker: smaller skill index). Otherwise, filters for offensive skills (fallback: all available) and picks the one maximizingpower * current_pp(tie-breaker: smaller skill index).ConjurerHunter: Ifpokemon.hp < pokemon.max_hpand at least one"Heal"skill is available, picks the"Heal"skill with the highestpower(tie-breaker: smaller skill index). Otherwise, filters for offensive skills (fallback: all available) and picks the one with the lowestmax_cd(tie-breaker: highestpower, then smaller skill index).SpecialistHunter: On every 3rd personal turn (turn_count % 3 == 0), picks from allavailable_skillsthe one with the highestmax_cd(tie-breaker: highestpower, then smaller skill index). On all other turns, picks from allavailable_skillsthe one with the lowestcurrent_pp(tie-breaker: highestpower, then smaller skill index).
- Each Hunter owns a
- Arena Loop (
BattleArena):- Loops global
turnfrom tomax_turns(inclusive). Before each turn, if either Pokémon hasis_alive == False, stops immediately. - Odd global turns:
hunter1.take_turn(hunter2); even global turns:hunter2.take_turn(hunter1). - After the loop, the Hunter whose Pokémon has strictly higher
hpwins; otherwise"Draw".
- Loops global
As a kind TA, Cabi has already written the skeleton structure for you, but some of the classes and methods are still missing. Your task is to complete those classes.
Variables
max_turns: maximum number of single-action turns in the battle (int).current_cd,current_pp: managed via@propertygetters and setters onSkill, automatically clamped to[0, max_cd]and[0, max_pp].is_available: read-only@propertyonSkillreturningbool(current_cd == 0 and current_pp > 0).hp: managed via@propertygetter and setter onPokemon, automatically clamped to[0, max_hp].is_alive: read-only@propertyonPokemonreturningbool(hp > 0).turn_count: personal action counter onHunter, initialized to0.
Example for the Battle Mechanics:
Suppose Gon (EnhancerHunter) commands Charizard (PowerPokemon, max_hp=120, atk=25, def=10) with Flamethrower (Attack, power=30, max_cd=2, max_pp=2) against Hisoka (TransmuterHunter) commanding Gengar (MysticPokemon, max_hp=110, atk=22, def=8):
- Global Turn 1 (Gon's Turn 1):
Gonpicks his highest-power offensive skillFlamethrower.PowerPokemonboosts"Attack"raw damage by :((25 + 30) * 12) // 10 = 66.Gengartakesmax(1, 66 - 8) = 58damage (hp: 110 -> 52). - Global Turn 2 (Hisoka's Turn 1): Being odd turn (
turn_count == 1),Hisokafeints with his lowest-power skillLick(power=12), dealingmax(1, (22 + 12) - 10) = 24damage (Charizard hp: 120 -> 96).
Classes to Implement
To build the arena, you need to implement the following classes and methods:
Skill:__init__(self, name: str, skill_type: str, power: int, max_cd: int, max_pp: int)@property& setters forcurrent_cdandcurrent_pp; read-only@propertyis_available.consume(self) -> Noneandtick_cooldown(self) -> None.@classmethod def from_string(cls, line: str) -> "Skill": Parses"<name> <skill_type> <power> <max_cd> <max_pp>".__repr__(self) -> str: ReturnsSkill(name='<name>', type='<skill_type>', power=<power>, cd=<current_cd>/<max_cd>, pp=<current_pp>/<max_pp>).
Pokemon(ABC)& Subclasses (PowerPokemon,MysticPokemon,TankPokemon):__init__(self, name: str, max_hp: int, atk: int, defense: int, skills: List[Skill])@property& setter forhp; read-only@propertyis_alive.prepare_turn(self) -> None,get_available_skills(self) -> List[Skill],heal(self, amount: int) -> None,take_damage(self, raw_dmg: int, ignore_def_half: bool = False) -> int,struggle(self, target: "Pokemon") -> None.@abstractmethod def execute_skill(self, skill: Skill, target: "Pokemon") -> Noneimplemented in each subclass.@classmethod def create(cls, poke_type: str, poke_name: str, max_hp: int, atk: int, defense: int, skills: List[Skill]) -> "Pokemon".__repr__(self) -> str: Returns<ClassName>(name='<name>', hp=<hp>/<max_hp>, atk=<atk>, def=<defense>).
Hunter(ABC)& Subclasses (EnhancerHunter,EmitterHunter,TransmuterHunter,ManipulatorHunter,ConjurerHunter,SpecialistHunter):__init__(self, name: str, nen_type: str, pokemon: Pokemon)andtake_turn(self, opponent: "Hunter") -> None.@abstractmethod def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]implemented in each subclass.@classmethod def create(cls, nen_type: str, hunter_name: str, pokemon: Pokemon) -> "Hunter".__repr__(self) -> str: Returns<ClassName>(name='<name>', turn=<turn_count>, pokemon=<repr(pokemon)>).
BattleArena:__init__(self, hunter1: Hunter, hunter2: Hunter, max_turns: int)andrun(self) -> str.
Template code
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Type
import sys
class Skill:
def __init__(self, name: str, skill_type: str, power: int, max_cd: int, max_pp: int):
# TODO
pass
@property
def current_cd(self) -> int:
# TODO
pass
@current_cd.setter
def current_cd(self, value: int) -> None:
# TODO
pass
@property
def current_pp(self) -> int:
# TODO
pass
@current_pp.setter
def current_pp(self, value: int) -> None:
# TODO
pass
@property
def is_available(self) -> bool:
# TODO
pass
def consume(self) -> None:
# TODO
pass
def tick_cooldown(self) -> None:
# TODO
pass
@classmethod
def from_string(cls, line: str) -> "Skill":
# TODO
pass
def __repr__(self) -> str:
# TODO
pass
class Pokemon(ABC):
def __init__(self, name: str, max_hp: int, atk: int, defense: int, skills: List[Skill]):
# TODO
pass
@property
def hp(self) -> int:
# TODO
pass
@hp.setter
def hp(self, value: int) -> None:
# TODO
pass
@property
def is_alive(self) -> bool:
# TODO
pass
def prepare_turn(self) -> None:
# TODO
pass
def get_available_skills(self) -> List[Skill]:
# TODO
pass
def heal(self, amount: int) -> None:
# TODO
pass
def take_damage(self, raw_dmg: int, ignore_def_half: bool = False) -> int:
# TODO
pass
def struggle(self, target: "Pokemon") -> None:
# TODO
pass
@abstractmethod
def execute_skill(self, skill: Skill, target: "Pokemon") -> None:
pass
@classmethod
def create(
cls,
poke_type: str,
poke_name: str,
max_hp: int,
atk: int,
defense: int,
skills: List[Skill],
) -> "Pokemon":
# TODO
pass
def __repr__(self) -> str:
# TODO
pass
class PowerPokemon(Pokemon):
def execute_skill(self, skill: Skill, target: "Pokemon") -> None:
# TODO
pass
class MysticPokemon(Pokemon):
def execute_skill(self, skill: Skill, target: "Pokemon") -> None:
# TODO
pass
class TankPokemon(Pokemon):
def take_damage(self, raw_dmg: int, ignore_def_half: bool = False) -> int:
# TODO
pass
def execute_skill(self, skill: Skill, target: "Pokemon") -> None:
# TODO
pass
class Hunter(ABC):
def __init__(self, name: str, nen_type: str, pokemon: Pokemon):
# TODO
pass
def take_turn(self, opponent: "Hunter") -> None:
# TODO
pass
@abstractmethod
def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]:
pass
@classmethod
def create(cls, nen_type: str, hunter_name: str, pokemon: Pokemon) -> "Hunter":
# TODO
pass
def __repr__(self) -> str:
# TODO
pass
class EnhancerHunter(Hunter):
def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]:
# TODO
pass
class EmitterHunter(Hunter):
def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]:
# TODO
pass
class TransmuterHunter(Hunter):
def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]:
# TODO
pass
class ManipulatorHunter(Hunter):
def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]:
# TODO
pass
class ConjurerHunter(Hunter):
def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]:
# TODO
pass
class SpecialistHunter(Hunter):
def choose_skill(self, available_skills: List[Skill], enemy_pokemon: Pokemon) -> Optional[Skill]:
# TODO
pass
class BattleArena:
def __init__(self, hunter1: Hunter, hunter2: Hunter, max_turns: int):
# TODO
pass
def run(self) -> str:
# TODO
pass
def parse_hunter(input_fn) -> Hunter:
h_name, nen_type = input_fn().split()
p_line = input_fn().split()
p_name, p_type = p_line[0], p_line[1]
max_hp, atk, defense, num_skills = map(int, p_line[2:])
skills = [Skill.from_string(input_fn()) for _ in range(num_skills)]
pokemon = Pokemon.create(p_type, p_name, max_hp, atk, defense, skills)
return Hunter.create(nen_type, h_name, pokemon)
if __name__ == "__main__":
input_fn = sys.stdin.readline
max_turns = int(input_fn().strip())
h1 = parse_hunter(input_fn)
h2 = parse_hunter(input_fn)
arena = BattleArena(h1, h2, max_turns)
winner = arena.run()
print(f"{h1.name} ({h1.pokemon.name}): {h1.pokemon.hp}/{h1.pokemon.max_hp}")
print(f"{h2.name} ({h2.pokemon.name}): {h2.pokemon.hp}/{h2.pokemon.max_hp}")
print(f"Winner: {winner}")
Input
The first line contains a single integer max_turns.
Then follow two Hunter blocks (for Hunter 1 and Hunter 2), each structured as:
- First line:
hunter_name nen_type(nen_type{"Enhancer", "Emitter", "Transmuter", "Manipulator", "Conjurer", "Specialist"}) - Second line:
poke_name poke_type max_hp atk defense num_skills(poke_type{"Power", "Mystic", "Tank"}) - Next
num_skillslines:skill_name skill_type power max_cd max_pp(skill_type{"Attack", "Pierce", "Heal"})
Constraints
- All names consist of alphanumeric characters without spaces.
Output
Output 3 lines:
- Line 1:
<hunter1_name> (<poke1_name>): <poke1_hp>/<poke1_max_hp> - Line 2:
<hunter2_name> (<poke2_name>): <poke2_hp>/<poke2_max_hp> - Line 3:
Winner: <winner_name_or_Draw>
Sample Input Download
Sample Output Download
Discuss
Description
Money's Battlefield
Money the capybara has become fascinated by turn-based strategy games. He wants to build a tiny battle simulator to study how cavalry, infantry, and archers behave. Instead of writing one giant block of conditional statements, Money dec
ides to model the units as objects with shared behaviors and different class bonuses.
Your task is to complete the simulator and print every soldier's HP and position after exactly T seconds.
The Battlefield
The battlefield has N rows and M columns. All coordinates are 1-based. There are P1 red soldiers and P2 blue soldiers. There are no obstacles. Any number of soldiers, including enemies, may occupy the same cell.
Soldier Attributes and Classes
Every soldier has an ID, team, HP, movement speed, attack damage, attack range, armor, and position (row, col). Three subclasses share the same basic behaviors:
- Cavalry (
C): actual speed = input speed multiplied byC_bonus. - Infantry (
I): initial HP = input HP multiplied byI_bonus. - Archer (
A): actual attack range = input range multiplied byA_bonus.
All three bonuses are input integers and apply equally to both teams. A unit's bonus is applied exactly once when the unit is created. All other attributes remain unchanged. Armor never receives a class bonus.
Distance and Target Selection
The distance between positions (r1,c1) and (r2,c2) is Manhattan distance:
distance = abs(r1 - r2) + abs(c1 - c2)
At the start of each action, a living soldier selects the closest living enemy. If multiple enemies are equally close, choose the one with the smallest global ID. The chosen target stays fixed during this action. If no living enemy exists, the soldier does nothing.
Order of Actions
Each of the T seconds consists of one Red Phase followed by one Blue Phase. Within each team, soldiers act in their original input order (increasing ID). Changes to HP and position take effect immediately. A soldier that dies before its turn is skipped.
Movement
Let D be the current distance to the chosen enemy, R the moving soldier's actual attack range, and S its actual movement speed.
If D <= R, the soldier does not move and attacks once. Otherwise it moves toward the target by exactly:
steps = min(S, D - R)
Move toward the target's row first until either the row matches or all movement steps are spent; then move toward the target's column with any remaining steps. This makes movement deterministic. The soldier stops as soon as it enters attack range, even if unused movement speed remains.
If it reaches attack range after moving, it attacks the same target immediately. A soldier can attack at most once per action.
Armor and Damage
Let K be the global armor coefficient, Damage the attacker's damage, and Armor the defender's armor. The integer damage taken is:
DamageTaken = max(1, (K * Damage) // (K + Armor))
The division uses integer floor, and every successful attack deals at least 1 point of damage. Update HP as:
HP = max(0, HP - DamageTaken)
When HP reaches zero, the soldier dies immediately. Dead soldiers neither act nor become targets, but their final position is retained and must still be output. If one team is eliminated, survivors do nothing for the remaining seconds.
Object-Oriented Programming Requirement
Implement the shared behavior in a Soldier base class, override apply_bonus in Cavalry, Infantry, and Archer, and manage the turn order in Battlefield. The starter code below includes the required attributes and method signatures; complete the TODO sections without changing the provided input/output format.
Starter Code (Python 3)
import sys
class Soldier:
def __init__(self, soldier_id, team, hp, speed, damage,
attack_range, armor, row, col):
# All soldiers share these attributes.
self.id = soldier_id
self.team = team
self.hp = hp
self.speed = speed
self.damage = damage
self.attack_range = attack_range
self.armor = armor
self.row = row
self.col = col
def is_alive(self):
# TODO: Return whether this soldier is alive.
pass
def distance_to(self, other):
# TODO: Return Manhattan distance to other.
pass
def find_target(self, enemies):
# TODO: Choose closest living enemy; ties -> smaller ID.
pass
def take_damage(self, raw_damage, k):
# TODO: Armor reduction, floor, minimum 1; HP cannot go below 0.
pass
def move_toward(self, target):
# TODO: Move row first, then column; stop at attack range.
pass
def attack(self, target, k):
# TODO: Attack target once if target is alive and in range.
pass
def act(self, enemies, k):
# TODO: Pick target, then attack or move (and attack if in range).
pass
class Cavalry(Soldier):
def apply_bonus(self, bonus):
# TODO: Multiply movement speed by bonus.
pass
class Infantry(Soldier):
def apply_bonus(self, bonus):
# TODO: Multiply initial HP by bonus.
pass
class Archer(Soldier):
def apply_bonus(self, bonus):
# TODO: Multiply attack range by bonus.
pass
class Battlefield:
def __init__(self, red, blue, k):
self.red = red
self.blue = blue
self.k = k
def run_phase(self, allies, enemies):
# TODO: Each living ally acts in input order.
pass
def simulate(self, t):
# TODO: Run T seconds; Red phase before Blue phase.
pass
def results(self):
# Provided output helper; do not change the format.
return "\n".join(
f"{unit.hp} {unit.row} {unit.col}"
for unit in self.red + self.blue
)
def read_soldier(soldier_id, team, bonuses):
parts = sys.stdin.buffer.readline().split()
kind = parts[0].decode()
hp, speed, damage, attack_range, armor, row, col = map(int, parts[1:])
classes = {'C': Cavalry, 'I': Infantry, 'A': Archer}
soldier = classes[kind](soldier_id, team, hp, speed, damage,
attack_range, armor, row, col)
soldier.apply_bonus(bonuses[kind])
return soldier
def main():
n, m, p1, p2, t = map(int, sys.stdin.buffer.readline().split())
k, c_bonus, i_bonus, a_bonus = map(int, sys.stdin.buffer.readline().split())
bonuses = {'C': c_bonus, 'I': i_bonus, 'A': a_bonus}
red = [read_soldier(i, 'R', bonuses) for i in range(1, p1 + 1)]
blue = [read_soldier(p1 + i, 'B', bonuses) for i in range(1, p2 + 1)]
battlefield = Battlefield(red, blue, k)
battlefield.simulate(t)
sys.stdout.write(battlefield.results() + '\n')
if __name__ == '__main__':
main()
Constraints
1 <= N, M <= 100001 <= P1, P2 <= 301 <= T <= 3001 <= HP, Speed, Damage, Range <= 100000 <= Armor <= 10001 <= K <= 10001 <= C_bonus, I_bonus, A_bonus <= 51 <= Row <= N,1 <= Column <= M- All input values are integers; all initial positions are valid.
Sample Explanation
The first sample has two red soldiers and one blue soldier. After applying class bonuses, the red cavalry has speed 2, the red infantry has 20 initial HP, and the blue archer has range 4.
During second 1, the cavalry moves from (1,1) to (1,3), the infantry moves from (4,7) to (3,7), and the blue archer attacks the closer cavalry for 6 damage.
During second 2, the cavalry moves from (1,3) to (1,4) and attacks the archer. The archer's armor reduces 12 raw damage to (100 * 12) // (100 + 50) = 8. The infantry moves to (2,7), and the archer attacks the cavalry again for 6 damage. Thus the final HP values are 8, 20, and 17.
Input
The first line contains five integers:
N M P1 P2 T
N and M are battlefield dimensions, P1 and P2 the red and blue soldier counts, and T the number of seconds.
The second line contains:
K C_bonus I_bonus A_bonus
K is the global armor coefficient. The other three values are the class multipliers for cavalry speed, infantry initial HP, and archer attack range.
The next P1 lines describe red soldiers. The following P2 lines describe blue soldiers. Each line contains:
Type HP Speed Damage Range Armor Row Column
Type is C, I, or A. All attributes on these lines are base values before class bonuses. Global IDs are assigned by input order, starting from 1 (all red soldiers appear first).
Sample Input
4 7 2 1 2
100 2 2 2
C 20 1 12 1 0 1 1
I 10 1 8 1 0 4 7
A 25 1 6 2 50 1 5
Output
After exactly T seconds, print P1 + P2 lines in the original input order.
Each line contains:
HP Row Column
HP is the remaining HP (0 for a dead soldier). A dead soldier keeps its last position. All positions are 1-based.
Sample Output
8 1 4
20 2 7
17 1 5
