// CF71D Solitaire
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// GLOBAL
int n, m, cnt;
std::string s[20][20];
std::set<std::string> cards;
int j1x = -1, j1y = -1, j2x = -1, j2y = -1;
bool Check(int x, int y)
{
std::map<char, bool> mp;
for (int i = x; i < x + 3; i++)
for (int j = y; j < y + 3; j++)
mp[s[i][j][0]] = true;
if ((int)mp.size() == 9)
return true;
mp.clear();
for (int i = x; i < x + 3; i++)
for (int j = y; j < y + 3; j++)
mp[s[i][j][1]] = true;
if ((int)mp.size() == 1)
return true;
return false;
}
void OutputSquares(int x1, int y1, int x2, int y2)
{
std::cout << "Put the first square to (" << x1 << ", " << y1 << ").\n";
std::cout << "Put the second square to (" << x2 << ", " << y2 << ").";
}
template <typename PrintFunc>
void FindTwoSquares(bool &flag, PrintFunc print)
{
for (int i1 = 1; i1 <= n - 2; i1++)
for (int j1 = 1; j1 <= m - 2; j1++)
if (Check(i1, j1))
for (int i2 = i1; i2 <= n - 2; i2++)
for (int j2 = (i2 == i1 ? j1 + 3 : 1); j2 <= m - 2; j2++)
if ((j2 > j1 + 2 || i2 > i1 + 2) && Check(i2, j2))
{
std::cout << "Solution exists.\n";
print();
OutputSquares(i1, j1, i2, j2);
flag = true;
return;
}
}
void SolveTwoJokers(bool &flag, const std::string &str1, const std::string &str2)
{
FindTwoSquares(flag, [&]()
{ std::cout << "Replace J1 with " << str1 << " and J2 with " << str2 << ".\n"; });
}
void SolveOneJoker(bool &flag, const std::string &str, bool isJ1)
{
FindTwoSquares(flag, [&]()
{ std::cout << "Replace J" << (isJ1 ? "1" : "2") << " with " << str << ".\n"; });
}
void SolveNoJoker(bool &flag)
{
FindTwoSquares(flag, []()
{ std::cout << "There are no jokers.\n"; });
}
int main()
{
// READ
std::cin >> n >> m;
std::string nums = "A23456789TJQK";
std::string cols = "CDHS";
for (char num : nums)
for (char col : cols)
cards.insert(std::string(1, num) + col);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
std::cin >> s[i][j];
if (s[i][j][0] == 'J' && (s[i][j][1] == '1' || s[i][j][1] == '2'))
{
cnt++;
if (s[i][j][1] == '1')
j1x = i, j1y = j;
else
j2x = i, j2y = j;
}
else
cards.erase(s[i][j]);
}
}
// MAIN
bool flag = false;
if (cnt == 2)
{
for (const std::string &str1 : cards)
if (!flag)
for (const std::string &str2 : cards)
if (!flag)
if (str1 != str2)
{
s[j1x][j1y] = str1;
s[j2x][j2y] = str2;
SolveTwoJokers(flag, str1, str2);
}
}
else if (cnt == 1)
{
bool isJ1 = (j1x != -1);
for (const std::string &str : cards)
{
if (!flag)
{
s[isJ1 ? j1x : j2x][isJ1 ? j1y : j2y] = str;
SolveOneJoker(flag, str, isJ1);
}
}
}
else
SolveNoJoker(flag);
if (!flag)
std::cout << "No solution.";
return 0;
}123
这是 2026年7月20日 存档的第 1 版,不是当前版本。查看当前版本