기본적인 분할정복 문제

 

문제 설명에서 어떻게 하라고 알려줘서 로직을 생각하기 쉬웠다.

#include <iostream>

using namespace std;

int n = 0;
int arr[129][129]{};
int resultWhite = 0, resultBlack = 0;

void Func(int startX, int startY, int endX, int endY) {
	int startColor = arr[startY][startX];
	bool shouldCut = false;

	for (int i = startY; i <= endY; ++i) {
		for (int j = startX; j <= endX; ++j) {
			if (startColor != arr[i][j]) {
				shouldCut = true;
				break;
			}
		}
		if (shouldCut)
			break;
	}

	if (shouldCut) {
		int halfX = (startX + endX) / 2;
		int halfY = (startY + endY) / 2;

		Func(startX, startY, halfX, halfY);
		Func(halfX + 1, startY, endX, halfY);
		Func(startX, halfY + 1, halfX, endY);
		Func(halfX + 1, halfY + 1, endX, endY);
	}
	else {
		if (startColor == 0) ++resultWhite;
		else ++resultBlack;
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> n;

	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n; ++j)
			cin >> arr[i][j];

	Func(0, 0, n - 1, n - 1);

	cout << resultWhite << "\n";
	cout << resultBlack << "\n";

	return 0;
}

 

'알고리즘 공부' 카테고리의 다른 글

백준 14503번 로봇 청소기 C++  (0) 2024.12.09
백준 2206번 벽 부수고 이동하기 C++  (0) 2024.12.08
백준 1238번 파티 C++  (0) 2024.11.24
백준 1002번 터렛 C++  (0) 2024.11.23
백준 12904번 A와 B C++  (0) 2024.11.15