차원이 h x w인 행렬이 주어졌다고 가정합니다. 매트릭스에는 영문자가 포함되어 있습니다. 회문 행과 열을 포함하는 또 다른 행렬을 만들어야 합니다. 즉, 각 행과 열은 회문입니다. 그렇게 하려면 주어진 행렬에서 행과 열의 모든 배열을 수행할 수 있습니다. 그러나 요소는 변경할 수 없습니다. 즉, 'a'를 'b'로 변경할 수 없습니다. 주어진 행렬에서 회문 행렬을 만드는 것이 가능하면 true를 반환합니다. 그렇지 않으면 false를 반환합니다.
따라서 입력이 h =4, w =4, mat ={"xxyy", "xyxx", "yxxy", "xyyy"}와 같으면 출력은 true가 됩니다.
단계
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
Define one map mp
Define an array count of size 4.
for initialize i := 0, when i < h, update (increase i by 1), do:
for initialize j := 0, when j < w, update (increase j by 1), do:
(increase tp[mat[i, j]] by 1)
for each value val in tp, do:
increase count[second value of val mod 4] by 1
check := true
if h mod 2 is same as 0 and w mod 2 is same as 0, then:
if count[1] + count[2] + count[3] > 0, then:
check := false
otherwise when h mod 2 is same as 1 and w mod 2 is same as 1, then:
if count[1] + count[3] > 1, then:
check := false
otherwise when count[2] > h / 2 + w / 2, then:
check := false
Otherwise
if count[1] + count[3] > 0, then:
check := false
otherwise when h mod 2 is same as 1 and count[2] > w / 2, then:
check := false
otherwise when w mod 2 is same as 1 and count[2] > h / 2, then:
check := false
return check 예
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
bool solve(int h, int w, vector<string> mat){
map<char, int> tp;
vector<int> count(4);
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j)
tp[mat[i][j]]++;
}
for (auto val : tp)
count[val.second % 4]++;
bool check = true;
if (h % 2 == 0 && w % 2 == 0) {
if (count[1] + count[2] + count[3] > 0)
check = false;
}
else if (h % 2 == 1 && w % 2 == 1) {
if (count[1]+count[3] > 1)
check = false;
else if (count[2] > h / 2 + w / 2)
check = false;
} else {
if (count[1] + count[3] > 0)
check = false;
else if (h % 2 == 1 && count[2] > w / 2)
check = false;
else if (w % 2 == 1 && count[2] > h / 2)
check = false;
}
return check;
}
int main() {
int h = 4, w = 4;
vector<string> mat = {"xxyy", "xyxx", "yxxy", "xyyy"};
cout<< solve(h, w, mat);
return 0;
} 입력
4, 4, {"xxyy", "xyxx", "yxxy", "xyyy"} 출력
1