习题6-9 UVA 127 纸牌游戏

一道学校OJ做的题目,当时卡了两三天。

简单说下题意:

52叠扑克,从左到右发现一个牌与他的前面3张或者1张 花色或者点数相同时,就把这张牌放到那上面,参与比较的只能是每一叠的第一章!

思路:

我建立了vector 套了一个stack  stack里面放了struct,先输入。

1.在输入方面,最好写个输入函数,真的很方便,在输入方面类似于紫书的例题6-7  UVA 122,写个输入函数比较巧妙!

2.然后从做到右扫描,没扫描的每一个进行检测,先检测前面第三张,发现可以放,就在检测,知道检测第三张不行了,在检测第一张,第一张可以在检测第三章,,,可以用个goto或者递归函数。

3.最后就是输出了,按照题目输出即可!


代码如下:

#include<vector>
#include<stack>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 70;
struct puk{
    char type,val;
    bool operator == (const puk &a)const {
        return a.type == type || a.val == val;
    }
    puk(char type,char val):type(type),val(val){}
};
vector<stack<puk> >sk;
bool read_input(){
    sk.clear();
    char s[maxn];
    for (int i = 0; i < 52; ++i){
        if (scanf("%s",s)!=1 || !strcmp(s,"#"))return false;
        stack<puk>sk_temp;
        sk_temp.push(puk(s[1],s[0]));
        sk.push_back(sk_temp);
    }
    return true;
}
int check_go(int pos){
    int cnt3=3,cnt1=1,com=pos;
    TT:
    int sum = 0;
    while(cnt3){
        while(pos > 0 && sk[pos-1].empty()){--pos;++sum;}
        if (pos>0){--pos;++sum;--cnt3;}
        if (pos <= 0)break;
    }
    if (!cnt3 && sk[pos].top() == sk[com].top()){cnt3=3;cnt1=1;goto TT;}
    pos+=sum;sum=0;
    while(cnt1){
        while(pos > 0 && sk[pos-1].empty()){--pos;++sum;}
        if (pos > 0){--pos;++sum;--cnt1;}
        if (pos<=0)break;
    }
    if (!cnt1 && sk[pos].top() == sk[com].top()){cnt3=3;cnt1=1;goto TT;}
    pos+=sum;
    return pos;
}
int main()
{
    while(read_input()){
        for (int i = 0; i < 52; ++i){
            if (sk[i].empty())continue;
            int ed = check_go(i);
            if (ed < i){
                puk temp = sk[i].top();
                sk[ed].push(temp);
                sk[i].pop();
                i=ed;
            }
        }
        int sum = 0;
        for (int i = 0; i < 52; ++i)if (!sk[i].empty())++sum;
        printf("%d %s remaining:",sum,sum == 1 ? "pile" : "piles");
        for (int i = 0; i < 52; ++i)
            if (!sk[i].empty())printf(" %d",(int)sk[i].size());
        printf("\n");
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值