其實這個題並不難,使用面向對象,按照題目思路一步一步走就可以拿到滿分。
爲了使代碼更加簡潔,我使用一個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);
}
}
}