斗地主之顺子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
#include <vector>
#include <list>
#include <sstream>
#include <algorithm>
#include <map>
using namespace std;

vector<vector<string >> MainData; // 全局变量,属于历史遗留问题,不希望改动太多代码的缘故

std::map<std::string, int> cardOrder = { // 建立映射关系
{"3", 1}, {"4", 2}, {"5", 3}, {"6", 4}, {"7", 5},
{"8", 6}, {"9", 7}, {"10", 8}, {"J", 9}, {"Q", 10},
{"K", 11}, {"A", 12}
};

bool isSort(const string &left, const string &right) {
return cardOrder[right] - cardOrder[left] == 1;
}

void getStraight(std::list<std::string> &data) {
std::vector<std::string> result;
for (auto it = data.begin(); it != data.end();) {
if (result.empty()) { // 暂时还没有元素
result.push_back(*it);
it = data.erase(it);
continue;
}
if (isSort(result.back(), *it)) {
result.push_back(*it);
it = data.erase(it);
} else {
it++;
}
}
if (result.size() >= 5) {
MainData.push_back(result);
}
}

template<typename T>
void Print(const T &data) {
for (const auto &i : data) {
cout << i << " ";
}
cout << "\n";
}

int main() {
std::string line;
getline(cin, line);
list<string> data;
istringstream iss(line);
string str;
while (iss >> str) {
if (str == "2") continue;
data.push_back(str);
}

if (data.size() < 5) {
cout << "No" << "\n";
return 0;
}

data.sort([](const auto &left, const auto &right) {
return cardOrder[left] < cardOrder[right];
});

while (data.size() >= 5) { // 收集顺子
getStraight(data);
}

if (MainData.empty()) {
cout << "No\n";
return 0;
}

sort(MainData.begin(), MainData.end()); // 非常关键,我认识是题目本身存在描述不清晰的问题
for (const auto &d : MainData) {
Print(d);
}

return 0;
}

在做这道题的时候,多次只能 AC 6道题目,但自己又感觉在逻辑上不可能存在问题。

终于,在网上找题解的过程中,我发现这个示例(官方没提供)并拿到自己的程序中测试,发现输出居然不一致。

这里的不一致指两个顺子的先后顺序不一致,先看看这个示例,再来说清楚:

1
2
3
4
5
6
输入:
3 3 4 4 5 5 6 6 7 7 8 8 9

输出:
3 4 5 6 7 8
3 4 5 6 7 8 9

拿到我的程序中运行,输出结果刚刚相反:

1
2
3 4 5 6 7 8 9
3 4 5 6 7 8

因此,我怀疑在输出上存在要求,但是题目中明显没有提到这件事情,可谓害人不浅。

看到有个题主在输出之前,会容器中存储的顺子集合会进行排序,我这边拿过来之后就 AC 通过了。

1
2
// 为了满足输出格式,这里必须排序
sort(MainData.begin(), MainData.end());