알고리즘 문제
[백준] 1780번 종이의 개수
feelcoding
2020. 4. 11. 20:58
728x90
https://www.acmicpc.net/problem/1780
1780번: 종이의 개수
N×N크기의 행렬로 표현되는 종이가 있다. 종이의 각 칸에는 -1, 0, 1의 세 값 중 하나가 저장되어 있다. 우리는 이 행렬을 적절한 크기로 자르려고 하는데, 이때 다음의 규칙에 따라 자르려고 한다. 만약 종이가 모두 같은 수로 되어 있다면 이 종이를 그대로 사용한다. (1)이 아닌 경우에는 종이를 같은 크기의 9개의 종이로 자르고, 각각의 잘린 종이에 대해서 (1)의 과정을 반복한다. 이와 같이 종이를 잘랐을 때, -1로만 채워진 종이의 개수, 0으
www.acmicpc.net
분할정복으로 9등분을 해가면서 풀면 된다.
그 나눠진 부분의 전체가 같은 수라면 재귀호출을 하지 않고 나눠진 부분에 있는 수들이 모두 같지 않으면 재귀호출을 해서 또 9등분을 하는 식으로 풀었따.
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> v;
int minusOne = 0;
int zero = 0;
int one = 0;
void divide(int rowStart, int rowEnd, int colStart, int colEnd, int width) {
int first = v[rowStart][colStart];
bool flag = true;
if (width != 1) {
for (int i = rowStart; i <= rowEnd; i++) {
for (int j = colStart; j <= colEnd; j++) {
if (first != v[i][j]) {
flag = false;
break;
}
}
if (!flag)
break;
}
}
if (flag) {
if (first == -1) {
minusOne++;
}
else if (first == 0) {
zero++;
}
else if (first == 1) {
one++;
}
}
else {
divide(rowStart, rowStart + width / 3 - 1, colStart, colStart + width / 3 - 1, width / 3);
divide(rowStart + width / 3, rowStart + width / 3 + width / 3 - 1, colStart, colStart + width / 3 - 1, width / 3);
divide(rowStart + width / 3 + width / 3, rowEnd, colStart, colStart+ width / 3 - 1, width / 3);
divide(rowStart, rowStart + width / 3 - 1, colStart + width / 3, colStart + width / 3 + width / 3 - 1, width / 3);
divide(rowStart + width / 3, rowStart + width / 3 + width / 3 - 1, colStart + width / 3, colStart + width / 3 + width / 3 - 1, width / 3);
divide(rowStart + width / 3 + width / 3, rowEnd, colStart + width / 3, colStart + width / 3 + width / 3 - 1, width / 3);
divide(rowStart, rowStart + width / 3 - 1, colStart + width / 3 + width / 3, colEnd, width / 3);
divide(rowStart + width / 3, rowStart + width / 3 + width / 3 - 1, colStart + width / 3 + width / 3, colEnd, width / 3);
divide(rowStart + width / 3 + width / 3, rowEnd, colStart + width / 3 + width / 3, colEnd, width / 3);
}
}
int main() {
int n;
cin >> n;
v = vector<vector<int>>(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> v[i][j];
}
}
divide(0, n - 1, 0, n - 1, n);
cout << minusOne << endl;
cout << zero << endl;
cout << one << endl;
return 0;
}
728x90