其实这个题并不难,使用面向对象,按照题目思路一步一步走就可以拿到满分。
为了使代码更加简洁,我使用一个HahsMap来存储先手玩家和后手玩家,键分别是1和-1,这样每次end的时候把当前玩家的键乘以-1就可以获得另一个玩家。召唤随从和攻击随从时题目给出的索引是从1开始的,所以我用一个list来存放玩家的英雄和随从,其中英雄的下标为0,随从的下标往后顺。
奉上java满分代码
import java.util.*;
public class Main {
static class Role {
public int health;
public int attack;
public boolean isHero;
public Role(int health, int attack) {
this.health = health;
this.attack = attack;
this.isHero = false;
}
public Role(int health, int attack, boolean isHero) {
this.health = health;
this.attack = attack;
this.isHero = isHero;
}
public void attack(Role role) {
this.health -= role.attack;
role.health -= this.attack;
}
public boolean isDead(){
return this.health <= 0;
}
}
private static HashMap<Integer, List<Role>> hashMap = new HashMap<>();
public static void main(String[] args) {
initMap();
List<String> lines = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
{
int n = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < n; i++) {
lines.add(scanner.nextLine());
}
}
scanner.close();
int no = 1;
for (String line : lines) {
String[] data = line.split(" ");
String type = data[0];
if (type.equals("end")) {
no *= -1;
} else if (type.equals("summon")) {
int position = Integer.parseInt(data[1]);
int attack = Integer.parseInt(data[2]);
int health = Integer.parseInt(data[3]);
hashMap.get(no).add(position, new Role(health, attack));
} else if (type.equals("attack")) {
Role attacker = hashMap.get(no).get(Integer.parseInt(data[1]));
Role defender = hashMap.get(no * -1).get(Integer.parseInt(data[2]));
attacker.attack(defender);
if (attacker.isDead())
hashMap.get(no).remove(attacker);
if (defender.isDead()) {
if (!defender.isHero) {
hashMap.get(no * -1).remove(defender);
} else {
break;
}
}
}
}
if (hashMap.get(1).get(0).isDead()) {
System.out.println(-1);
} else if (hashMap.get(-1).get(0).isDead()) {
System.out.println(1);
} else {
System.out.println(0);
}
printMap();
}
private static void printMap(){
for (int no : new int[]{1, -1}) {
List<Role> roles = hashMap.get(no);
System.out.println(roles.get(0).health);
int count = 0;
StringBuffer stringBuffer = new StringBuffer();
for(int i = 1; i < 8; i++){
if(roles.get(i) != null){
count++;
stringBuffer.append(" " + roles.get(i).health);
}
}
System.out.println(count + stringBuffer.toString());
}
}
private static void initMap() {
for (int no : new int[]{1, -1}) {
List<Role> roles = new ArrayList<>();
roles.add(new Role(30, 0, true));
for (int i = 0; i < 7; i++) {
roles.add(null);
}
hashMap.put(no, roles);
}
}
}