题解:UVA170 Clock Patience

· · 题解

思路

这题最容易错的地方是输入顺序吧。题目说第一张发出的牌是输入的最后一张,所以读入顺序存进 a[0...51] 后,第 k 张发出的牌是 a[52-k],它会被放到第 (k-1)%13+1 堆,其中 1 ~ 12 对应 A ~ Q,13 对应中心的 K 堆。

每堆需要从堆顶取牌、往堆底放牌,所以用 deque,让 front() 是堆顶:发牌时就用 pushfront,翻开后放回对应堆底时就用 pushback。

初始当前牌取 K 堆堆顶。之后循环,翻开当前牌并计数,把它放到对应点数堆的堆底,再取该堆堆顶作为新的当前牌。当新当前牌已经被翻开过时停止,输出计数和这张牌。

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=14;
int gp(string s){//把牌面转成点数,A~K 对应 1~13
    char c=s[0];
    if(c=='A')return 1;
    if(c=='T')return 10;
    if(c=='J')return 11;
    if(c=='Q')return 12;
    if(c=='K')return 13;
    return c-'0';
}
int main(){
    string s;
    while(cin>>s&&s!="#"){
        vector<string>a;
        a.push_back(s);
        for(int i=1;i<52;i++){
            cin>>s;
            a.push_back(s);
        }
        deque<string>d[maxn];
        for(int k=1;k<=52;k++){
            int p=(k-1)%13+1;
            d[p].push_front(a[52-k]);//倒序发牌
        }
        set<string>h;//记录已经翻开过的牌
        string c=d[13].front();//初始从 K 堆堆顶取牌
        d[13].pop_front();
        int t=0;
        while(1){
            t++;//翻开当前牌,计数
            h.insert(c);
            int p=gp(c);//当前牌点数决定放到哪堆
            d[p].push_back(c);//放到对应堆的堆底
            c=d[p].front();//取该堆堆顶作为新的当前牌
            d[p].pop_front();
            if(h.count(c)){//新当前牌已经翻开过,结束
                cout<<setw(2)<<setfill('0')<<t<<","<<c<<endl;
                break;
            }
        }
    }
    return 0;
}