문제 링크입니다: https://www.acmicpc.net/problem/14391
14391번: 종이 조각
영선이는 숫자가 쓰여 있는 직사각형 종이를 가지고 있다. 종이는 1×1 크기의 정사각형 칸으로 나누어져 있고, 숫자는 각 칸에 하나씩 쓰여 있다. 행은 위에서부터 아래까지 번호가 매겨져 있고,
www.acmicpc.net
이 문제의 핵심은 정사각형 칸을 어떻게 쪼갤 것인지를 구현하는 과정에 있었습니다.
아래와 같이 비트마스킹을 이용하여 모든 경우의 수를 탐색하면 풀 수 있습니다.
- 0: 숫자를 가로로 이어 붙인다
- 1: 숫자를 세로로 이어 붙인다

위 표를 비트마스킹으로 구현하면 아래와 같습니다.
- 0001110111110011
위 비트를 주어진 N, M을 기반으로 표로 만들면 다음과 같습니다.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
const int MAX = 4; | |
int N, M; | |
int result; | |
int board[MAX][MAX]; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
cin >> N >> M; | |
for (int y = 0; y < N; y++) | |
{ | |
string s; | |
cin >> s; | |
for (int x = 0; x < M; x++) | |
{ | |
board[y][x] = (s[x] - '0'); | |
} | |
} | |
for (int bit = 0; bit < (1 << (N * M)); bit++) | |
{ | |
int sum = 0; | |
for (int y = 0; y < N; y++) | |
{ | |
int temp = 0; | |
for (int x = 0; x < M; x++) | |
{ | |
int k = y * M + x; | |
if (!(bit & (1 << k))) | |
{ | |
temp *= 10; | |
temp += board[y][x]; | |
} | |
else | |
{ | |
sum += temp; | |
temp = 0; | |
} | |
} | |
sum += temp; | |
} | |
for (int x = 0; x < M; x++) | |
{ | |
int temp = 0; | |
for (int y = 0; y < N; y++) | |
{ | |
int k = y * M + x; | |
if (bit & (1 << k)) | |
{ | |
temp *= 10; | |
temp += board[y][x]; | |
} | |
else | |
{ | |
sum += temp; | |
temp = 0; | |
} | |
} | |
sum += temp; | |
} | |
result = max(result, sum); | |
} | |
cout << result << "\n"; | |
return 0; | |
} |

개발환경:Visual Studio 2022
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
참고
인프런 10주완성-코딩테스트 - 큰돌 강사님
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 13244번 Tree (0) | 2024.03.31 |
---|---|
백준 14405번 피카츄 (0) | 2024.03.31 |
백준 1285번 동전 뒤집기 (0) | 2024.03.30 |
백준 19942번 다이어트 (1) | 2024.03.30 |
백준 1189번 컴백홈 (0) | 2024.03.27 |