
열을 기준으로 최빈값인 문자들을 조합해 최적의 문자열을 만드는 것이 핵심이었다.
문제를 처음에 잘못 이해해서 잘못 풀었던...
map<char, int>는 DefaultDict처럼 value인 int값이 0으로 시작하는 것이 특징이다.
map['c']++; 도 가능하다.
해결한 코드는 아래와 같다.
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
cin >> n;
cin >> m;
vector<string> vec;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
vec.push_back(s);
}
string result_str = "";
for (int j = 0; j < m; j++) {
map<char, int> map;
for (int i = 0; i < n; i++) {
map[vec[i][j]]++;
}
char best_char = 'A';
int best_cnt = 0;
for (auto &p : map) {
if (p.second > best_cnt) {
best_char = p.first;
best_cnt = p.second;
} else if (p.second == best_cnt && p.first < best_char) {
best_char = p.first;
}
}
result_str += best_char;
}
cout << result_str << endl;
int result_cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (vec[i][j] != result_str[j]) {
result_cnt++;
}
}
}
cout << result_cnt << endl;
}'Algorithm > BOJ' 카테고리의 다른 글
| [백준] 18258번 Silver 4 큐 2, C++ 코드 (0) | 2025.12.11 |
|---|---|
| [백준] 1021번 Silver3 회전하는 큐, C++ 코드 (0) | 2025.12.10 |
| [백준] 17413번 Silver 3 단어 뒤집기 2, C++ 코드 (0) | 2025.12.08 |
| [백준] 1629번 Silver 1 곱셈, Java 코드 (0) | 2024.10.06 |
| [백준] 1149번 - Silver 1 RGB거리, 파이썬 코드 (0) | 2024.09.30 |