啊哈算法-紙牌游戲-小貓釣魚


紙牌游戲——小貓釣魚


  星期天小哼和小哈約在一起玩桌游,他們正在玩一個非常古怪的撲克游戲——“小貓釣魚”。游戲的規則是這樣的:將一副撲克牌平均分成兩份,每人拿一份。小哼先拿出手中的第一張撲克牌放在桌上,然后小哈也拿出手中的第一張撲克牌,並放在小哼剛打出的撲克牌的上面,就像這樣兩人交替出牌。出牌時,如果某人打出的牌與桌上某張牌的牌面相同,即可將兩張相同的牌及其中間所夾的牌全部取走,並依次放到自己手中牌的末尾。當任意一人手中的牌全部出完時,游戲結束,對手獲勝。(牌面為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
小哈贏了 
*/ 

跟書上不一樣的結果,但是原理一樣。具體問題還不太清楚是什么情況。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM