P11227 [CSP-J 2024] 扑克牌

· · 题解

P11227 [CSP-J 2024] 扑克牌

我们先看一下题目

T1

这道题是用哈希(Hash)来节省时间的一道题,

题目大意是有一副可能不完整的扑克牌,一副完整的扑克牌有52张,每种花色和点数恰好有一张牌。要去小S那里借牌,使得不完整的牌一起能构成一副完整的扑克牌。问至少需要向小S借多少张牌。

我的思路如下:

  1. 数据初始化:使用一个数组或哈希表来记录每种花色和点数的牌是否已经存在。处理重复牌。
  2. 遍历输入牌:对于输入的每张牌,更新记录,标记该花色和点数的牌为已存在。
  3. 计算缺少的牌数:遍历所有可能的花色和点数组合,统计哪些组合在输入中没有出现,这些就是需要借的牌。

50分做法:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    string s[10001];
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>s[i];
    }
    cout<<52-n;
    return 0;
}

简单,但分数低,因为这道题要考虑重复的扑克牌

100分解法:

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    cin >> n;
    int hash[53] = {0};
    for(int i = 0;i<n;i++){
        string s;
        cin >> s;
        // D C H S
        // A23456789TJQK
        int index_j = -1;
        if(s[1] == 'A'){
            index_j = 1;
        }   
         else if(s[1] == 'T'){
            index_j = 10;
        } else if(s[1] == 'J'){
            index_j = 11;
        } else if(s[1] == 'Q'){
            index_j = 12;
        } else if(s[1] == 'K'){
            index_j = 13;
        } else{
            index_j = s[1] - '0';
        }

        int index_i = -1;
        if(s[0] == 'D'){
            index_i = 1;
        } else if(s[0] == 'C'){
            index_i = 14;
        } else if(s[0] == 'H'){
            index_i = 27;
        } else{
            index_i = 40;
        }
        hash[index_i + index_j - 1] += 1;
    }
    int cnt = 0;
    for(int i = 1;i<=52;i++){
        if(hash[i] >= 1){
            cnt++;
        }
    }
    cout << 52 - cnt << endl;
    return 0;
}

也可以用map

#include<bits/stdc++.h>
using namespace std;
map<string,bool>S;
int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
        {
            string s;
        cin>>s;
        S[s]=1;
    }
    cout<<52-S.size();
    return 0;
}

好了,这篇题解就到这了,你今年CSP-J考的又怎样呢?

莫笑农家腊酒浑,丰年留客足鸡豚。
山重水复疑无路,柳暗花明又一村。
箫鼓追随春社近,衣冠简朴古风存。
从今若许闲乘月,拄杖无时夜叩门。
                       ——陆游