Question
星期天小哼和小哈约在一起玩桌游,他们正在玩一个非常古怪的扑克游戏——“小猫钓鱼”。游戏的规则是这样的:将一副扑克牌平均分成两份,每人拿一份。小哼先拿出手中的第一张扑克牌放在桌上,然后小哈也拿出手中的第一张扑克牌,并放在小哼刚打出的扑克牌的上面,就像这样两人交替出牌。出牌时,如果某人打出的牌与桌上某张牌的牌面相同,即可将两张相同的牌及其中间所夹的牌全部取走,并依次放到自己手中牌的末尾。当任意一人手中的牌全部出完时,游戏结束,对手获胜。
假如游戏开始时,小哼手中有6 张牌,顺序为2 4 1 2 5 6,小哈手中也有6 张牌,顺序为3 1 3 5 6 4,最终谁会获胜呢?现在你可以拿出纸牌来试一试。接下来请你写一个程序来自动判断谁将获胜。这里我们做一个约定,小哼和小哈手中牌的牌面只有1~9。
Analysis
我们先来分析一下这个游戏有哪几种操作。小哼有两种操作,分别是出牌和赢牌。这恰好对应队列的两个操作,出牌就是出队,赢牌就是入队。小哈的操作和小哼是一样的。而桌子就是一个栈,每打出一张牌放到桌上就相当于入栈。当有人赢牌的时候,依次将牌从桌上拿走,这就相当于出栈。那如何解决赢牌的问题呢?赢牌的规则是:如果某人打出的牌与桌上的某张牌相同,即可将两张牌以及中间所夹的牌全部取走。那如何知道桌上已经有哪些牌了呢?最简单的方法就是枚举桌上的每一张牌,当然也有更好的办法我们待会再说。OK,小结一下,我们需要两个队列、一个栈来模拟整个游戏。
Input & Output
[Input Example]
2 4 1 2 5 63 1 3 5 6 4
[Output Example]
小哼win小哼手中的牌是:5 6 2 3 1 4 6 5桌上的牌是:2 1 3 4
Solution
import java.util.Scanner;public class card_fishing{static int N = 12;static int[] queue1 = new int[12]; //小哼手中的牌static int head1 = 0, tail1 = 0;static int[] queue2 = new int[12]; //小哈手中的牌static int head2 = 0, tail2 = 0;static int[] stack = new int[9]; //桌上的牌static int top = 0;static boolean[] book = new boolean[10]; //标记哪些牌在桌上public static void main(String[] args){Scanner sc = new Scanner(System.in);//小哼手中的牌for(int i=0; i<6; i++){queue1[tail1] = sc.nextInt();tail1 = (tail1 + 1) % N;}//小哈手中的牌for(int i=0; i<6; i++){queue2[tail2] = sc.nextInt();tail2 = (tail2 + 1) % N;}sc.close();while(head1!=tail1 && head2!=tail2){//小哼出牌int temp = queue1[head1];//桌上没有这张牌if(!book[temp]){//出队、入栈head1 = (head1 + 1) % N;stack[++top] = temp;book[temp] = true;}else{//出队、入队head1 = (head1 + 1) % N;queue1[tail1] = temp;tail1 = (tail1 + 1) % N;//出栈、入队while(stack[top] != temp){book[stack[top]] = false;queue1[tail1] = stack[top];tail1 = (tail1 + 1) % N;top--;}}temp = queue2[head2];if(!book[temp]){head2 = (head2 + 1) % N;stack[++top] = temp;book[temp] = true;}else{head2 = (head2 + 1) % N;queue2[tail2] = temp;tail2 = (tail2 + 1) % N;while(stack[top] != temp){book[stack[top]] = false;queue2[tail2] = stack[top];tail2 = (tail2 + 1) % N;top--;}}}if(head2 == tail2){System.out.println("小哼win");System.out.println("小哼手中的牌是:");for(int i=head1; i!=tail1; i=(i+1)%N)System.out.print(queue1[i] + " ");System.out.println();if(top > 0) //如果桌上有牌则依次输出桌上的牌{System.out.println("桌上的牌是:");for(int i=1;i<=top;i++)System.out.print(stack[i] + " ");}elseSystem.out.println("桌上已经没有牌了");}else{System.out.println("小哈win");System.out.println("小哈手中的牌是:");for(int i=head2; i!=tail2; i=(i+1)%N)System.out.print(queue2[i] + " ");System.out.println();if(top > 0) //如果桌上有牌则依次输出桌上的牌{System.out.println("桌上的牌是:");for(int i=1;i<=top;i++)System.out.print(stack[i] + " ");}elseSystem.out.println("桌上已经没有牌了");}}}
