一群孩子想要玩一款名为UnMonopoly的游戏,其中每次转动玩家最多的钱必须以最少的钱给玩家一半的钱。轮流完成后,宣布最高钱的人为WINNER。通过获得转数和玩家来实现这个游戏。 (提示:使用优先级队列)
示例输入:
球员数量:n
转数:m
输入每位玩家的详细信息和金钱
输出:
获胜者是:玩家姓名
这是我的问题,我写了一段代码。这是一种正确的实施方式,还是存在任何缺陷。是否有更好的实施,时间复杂度更小?
这是我的代码,
import java.util.*;
class Player implements Comparator<Player> {
String name;
int money;
Player(String name, int m) {
this.name = name;
money = m;
}
public Player() {
this.money = 0;
this.name = null;
}
public String toString() {
return "NAME: "+name+"\nMONEY: "+money;
}
public int compare(Player p1, Player p2) {
return p2.money - p1.money;
}
}
public class Unmonopoly {
public static void main(String[] args) {
Player pl = new Player();
Stack<Player> pla = new Stack<Player>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of players: ");
int n = sc.nextInt();
PriorityQueue<Player> play = new PriorityQueue<Player>(n,pl);
System.out.println("Enter player details: ");
for(int i = 0; i < n; i++) {
Player p = new Player(sc.next(),sc.nextInt());
play.add(p);
}
for(Player p: play) {
System.out.println("Name: "+p.name+"\nMoney: "+p.money);
}
System.out.println("\nEnter the number of turns: ");
int turns = sc.nextInt();
for(int i = 0; i < turns; i++) {
Player max = play.peek();
max.money = max.money / 2;
while(!play.isEmpty()) {
pla.push(play.peek());
play.remove();
}
Player min = pla.pop();
pla.push(min);
System.out.println("Player with min money is: \n"+min);
min.money = min.money + max.money;
while(!pla.isEmpty()) {
play.add(pla.peek());
pla.pop();
}
}
sc.close();
System.out.println("**************WINNER************** \n\n\tNAME: "+play.peek().name+"\n\tMONEY: "+play.peek().money);
}
}
答案 0 :(得分:0)
您的复杂性为O(N * M * log(N)),因为您每回合都会重新创建优先级队列。
不确定提示的有效性,因为每回合都需要最小和最大玩家,因此更好的数据结构可能是TreeSet - 它允许您直接达到最小值和最大值。那么复杂性将是O(M * log(N))..
这种情况下的主循环只是:
for (int i = 0; i < turns; i++) {
Player min = players.pollFirst();
Player max = players.pollLast();
min.money += max.money / 2;
max.money -= max.money / 2;
players.add(min);
players.add(max);
}
poll
次操作以及add
都是O(log(N))..