๋ถํ ์ ๋ณต(Divide and Conquer)
๋ง ๊ทธ๋๋ ๋ฌธ์ ๋ฅผ ๋ถํ ๊ณผ ์ ๋ณต์ผ๋ก ๋๋ ์ ํด๊ฒฐํ๋ ๊ฒ์ ๋งํ๋ค.
- ๋ถํ ๋จ๊ณ์์๋ ์ฃผ์ด์ง ๋ฌธ์ ๋ฅผ ์ฌ๋ฌ ๊ฐ์ ๋ถ๋ถ ๋ฌธ์ ๋ค๋ก ๋๋๋๋ฐ, ๋ฌธ์ ๊ฐ ์์์ง์๋ก ํ๊ธฐ ์ฌ์์ง๊ธฐ ๋๋ฌธ์ด๋ค.
- ๋์ฒด๋ก ๋ถํ ์ ๋ณต์ ์ฌ๊ท ํธ์ถ์ ์ฌ์ฉํ๋ค.
๋ฌธ์
https://www.acmicpc.net/problem/1992
1992๋ฒ: ์ฟผ๋ํธ๋ฆฌ
์ฒซ์งธ ์ค์๋ ์์์ ํฌ๊ธฐ๋ฅผ ๋ํ๋ด๋ ์ซ์ N ์ด ์ฃผ์ด์ง๋ค. N ์ ์ธ์ ๋ 2์ ์ ๊ณฑ์๋ก ์ฃผ์ด์ง๋ฉฐ, 1≤N ≤64์ ๋ฒ์๋ฅผ ๊ฐ์ง๋ค. ๋ ๋ฒ์งธ ์ค๋ถํฐ๋ ๊ธธ์ด N ์ ๋ฌธ์์ด์ด N ๊ฐ ๋ค์ด์จ๋ค. ๊ฐ ๋ฌธ์์ด์ 0 ๋๋ 1์ ์ซ์๋ก ์ด๋ฃจ์ด์ ธ ์์ผ๋ฉฐ, ์์์ ๊ฐ ์ ๋ค์ ๋ํ๋ธ๋ค.
www.acmicpc.net
#include <iostream>
#include <cmath>
using namespace std;
int board[64][64];
void f(int n, int x, int y)
{
bool color = board[y][x];
bool diff = false;
for (int i = y; i < n + y; ++i) {
for (int j = x; j < n + x; ++j)
if (color != board[i][j]) {
diff = true;
break;
}
if (diff)
break;
}
if (!diff) {
cout << color;
return;
}
cout << "(";
f(n / 2, x, y);
f(n / 2, x + n / 2, y);
f(n / 2, x, y + n / 2);
f(n / 2, x + n / 2, y + n / 2);
cout << ")";
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
scanf("%1d", &board[i][j]);
f(n, 0, 0);
}
https://www.acmicpc.net/problem/1780
1780๋ฒ: ์ข ์ด์ ๊ฐ์
N×Nํฌ๊ธฐ์ ํ๋ ฌ๋ก ํํ๋๋ ์ข ์ด๊ฐ ์๋ค. ์ข ์ด์ ๊ฐ ์นธ์๋ -1, 0, 1์ ์ธ ๊ฐ ์ค ํ๋๊ฐ ์ ์ฅ๋์ด ์๋ค. ์ฐ๋ฆฌ๋ ์ด ํ๋ ฌ์ ์ ์ ํ ํฌ๊ธฐ๋ก ์๋ฅด๋ ค๊ณ ํ๋๋ฐ, ์ด๋ ๋ค์์ ๊ท์น์ ๋ฐ๋ผ ์๋ฅด๋ ค๊ณ ํ๋ค.
www.acmicpc.net
#include <iostream>
using namespace std;
int board[2190][2190];
int ans[3];
void f(int n, int x, int y)
{
if (n == 1) {
ans[board[y][x] + 1]++;
return;
}
int tmp = board[y][x];
bool diff = false;
for (int i = y; i < n + y; ++i) {
for (int j = x; j < n + x; ++j)
if (tmp != board[i][j]) {
diff = true;
break;
}
if (diff)
break;
}
if (!diff) {
ans[tmp + 1]++;
return;
}
n /= 3;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
f(n, x + n * j, y + n * i);
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
scanf("%d", &board[i][j]);
f(n, 0, 0);
cout << ans[0] << "\n" << ans[1] << "\n" << ans[2];
}
https://leetcode.com/problems/different-ways-to-add-parentheses/description/
#include <unordered_map>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
unordered_map<string, vector<int>> hash;
vector<int> diffWaysToCompute(string expression) {
if (hash.find(expression) != hash.end())
return hash[expression];
vector<int> result;
for (int i = 0; i < expression.size(); ++i) {
char c = expression[i];
if (c == '+' || c == '-' || c == '*') {
string left = expression.substr(0, i);
string right = expression.substr(i + 1);
vector<int> leftResults = diffWaysToCompute(left);
vector<int> rightResults = diffWaysToCompute(right);
for (int l : leftResults) {
for (int r : rightResults) {
if (c == '+') {
result.push_back(l + r);
}
else if (c == '-') {
result.push_back(l - r);
}
else if (c == '*') {
result.push_back(l * r);
}
}
}
}
}
if (result.empty())
result.push_back(stoi(expression));
hash[expression] = result;
return result;
}
};