啊哈算法-纸牌游戏-小猫钓鱼

纸牌游戏——小猫钓鱼


  星期天小哼和小哈约在一起玩桌游,他们正在玩一个非常古怪的扑克游戏——“小猫钓鱼”。游戏的规则是这样的:将一副扑克牌平均分成两份,每人拿一份。小哼先拿出手中的第一张扑克牌放在桌上,然后小哈也拿出手中的第一张扑克牌,并放在小哼刚打出的扑克牌的上面,就像这样两人交替出牌。出牌时,如果某人打出的牌与桌上某张牌的牌面相同,即可将两张相同的牌及其中间所夹的牌全部取走,并依次放到自己手中牌的末尾。当任意一人手中的牌全部出完时,游戏结束,对手获胜。(牌面为1~9)

数据输入: 第一行分别为为小哼、小哈手中牌的数目,第二行是小哼手中的牌,第三行是小哈手中的牌,不同牌之间用空格隔开。
数据输出: 第一行是胜利者、

#include<stdio.h>
#include<string.h>
typedef struct somebody{
    int a[1005];
    int head=1;
    int tail=1;
}sb;
sb heng,ha;
int b[10],tem[10005],tail,flag_heng;//b查重  tem用来存放出现过但未收回的牌堆;
int main(){
    scanf("%d",&tail);//共有tail张牌
    for(int i=1;i<=tail;i++) scanf("%d",&heng.a[i]);
    for(int i=1;i<=tail;i++) scanf("%d",&ha.a[i]);
    heng.tail=tail;
    ha.tail=tail;
    tail=0;
    while(ha.tail>=ha.head){
        if(b[heng.a[heng.head]]==1){//小哼出牌并且查到牌堆有重复 
            heng.a[++heng.tail]=heng.a[heng.head];//拿走刚刚出的牌 
            while(heng.a[heng.head]!=tem[tail]){//拿到相同牌为止 
                b[tem[tail]]=0;//将牌堆设置为不再有拿走的牌 
                heng.a[++heng.tail]=tem[tail--];
            }
            heng.head++;//出牌 
            b[tem[tail]]=0;
            heng.a[++heng.tail]=tem[tail--];//拿走相同牌 
        }
        else{
            b[heng.a[heng.head]]=1;
            tem[++tail]=heng.a[heng.head++];//小哼没有查到重复牌 
        }
        if(heng.head>heng.tail){//小哼没牌了 
            flag_heng=1;
            printf("小哈赢了!");
            break;
        }
        if(b[ha.a[ha.head]]==1){//小哈出牌并且查到牌堆有重复 
            ha.a[++ha.tail]=ha.a[ha.head];//拿走刚刚出的牌 
            while(ha.a[ha.head]!=tem[tail]){//拿到相同牌为止
                b[tem[tail]]=0;//将牌堆设置为不再有拿走的牌 
                ha.a[++ha.tail]=tem[tail--];
            }
            ha.head++;//出牌 
            b[tem[tail]]=0; //拿走相同牌 
            ha.a[++ha.tail]=tem[tail--];
        }
        else{
            b[ha.a[ha.head]]=1;
            tem[++tail]=ha.a[ha.head++];//小哈没有查到重复牌
        }
    }
    if(flag_heng==0) printf("小哼赢了!");//小哈没牌了 
    return 0;
}
//测试数据
/*
6
2 4 1 2 5 6
3 1 3 5 6 4
小哈赢了 
*/ 

跟书上不一样的结果,但是原理一样。具体问题还不太清楚是什么情况。

posted @ 2021-12-12 23:06  m2on  阅读(767)  评论(0编辑  收藏  举报