[백준 14391번 C/C++] 종이 조각
[백준 14391번 C/C++] 종이 조각

https://www.acmicpc.net/problem/14391
해결전략
비트마스킹 Bitmasking
정답코드
#include <iostream> #include <vector> #include <algorithm> using namespace std; int n, m; int answer = 0; vector<vector<int>> v; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> m; v.resize(n, vector<int>(m)); for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { char c; cin >> c; v[y][x] = c - '0'; // 문자를 숫자로 변환 } } // Rule 정하기: 0이면 세로, 1이면 가로 // 총 2^(n*m) 경우의 수를 비트마스크로 표현 for (unsigned int bitmask = 0; bitmask < (1 << (n * m)); bitmask++) { int totalSum = 0; // 가로 합 계산 for (int y = 0; y < n; y++) { int rowSum = 0; for (int x = 0; x < m; x++) { int idx = y * m + x; if (bitmask & (1 << idx)) { // 가로로 합산 rowSum = rowSum * 10 + v[y][x]; } else { totalSum += rowSum; rowSum = 0; } } totalSum += rowSum; // 마지막에 남은 숫자 추가 } // 세로 합 계산 for (int x = 0; x < m; x++) { int colSum = 0; for (int y = 0; y < n; y++) { int idx = y * m + x; if ((bitmask & (1 << idx)) == 0) { // 세로로 합산 colSum = colSum * 10 + v[y][x]; } else { totalSum += colSum; colSum = 0; } } totalSum += colSum; // 마지막에 남은 숫자 추가 } answer = max(answer, totalSum); } cout << answer << '\n'; return 0; }
'⭐ 코딩테스트 > 백준' 카테고리의 다른 글
[백준 1062번 C/C++] 가르침 (0) | 2024.08.19 |
---|---|
[백준 2098번 C/C++] 외판원 순회 (0) | 2024.08.08 |
[백준 15661번 C++] 링크와 스타트 (0) | 2024.08.06 |
[백준 11723번 C/C++] 집합 (0) | 2024.08.05 |
[백준 1052번 C/C++] 물병 (0) | 2024.08.05 |
댓글
이 글 공유하기
다른 글
-
[백준 1062번 C/C++] 가르침
[백준 1062번 C/C++] 가르침
2024.08.19[백준 1062번 C/C++] 가르침 https://www.acmicpc.net/problem/1062 해결전략 비트마스킹 Bitmasking백트래킹 정답 코드 #include #include #include #include #include using namespace std;int n, k; // n: 단어의 수, k: 배울 수 있는 알파벳의 수int answer; // 최대 읽을 수 있는 단어의 수를 저장하는 변수int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> k; vector words(n); // 단어들을 저장할 벡터 for (int i = 0; i >… -
[백준 2098번 C/C++] 외판원 순회
[백준 2098번 C/C++] 외판원 순회
2024.08.08[백준 2098번 C/C++] 외판원 순회 https://www.acmicpc.net/problem/2098 해결전략 비트마스킹 Bitmasking동적계획법 Dynamic Programming, DP비트필드를 이용한 다이나믹 프로그래밍 외판원 순회 문제 정답 코드 #include #include #include using namespace std;int n; // 도시의 수vector> W; vector> dp;const int INF = 2147000000;int TSP(int cur, int visited){ // visited의 모든 비트가 1이라면(즉, 모든 도시를 방문했다면), 현재 도시에서 시작 도시로 돌아가는 비용을 반환 if (visited == (1 > n; W.res… -
[백준 15661번 C++] 링크와 스타트
[백준 15661번 C++] 링크와 스타트
2024.08.06 -
[백준 11723번 C/C++] 집합
[백준 11723번 C/C++] 집합
2024.08.05[백준 11723번 C/C++] 집합 https://www.acmicpc.net/problem/11723 해결전략 비트마스킹 Bitmasking 정답 코드 #include using namespace std;int m;int answer;int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> m; string input, int x; for (int i = 0; i > input; if (input == "add"){ cin >> x; answer |= (1 > x; answer &= ~(1 > x; if (answer & (1 > x; answer ^= (1
댓글을 사용할 수 없습니다.