[ 풀이 방법 ]
1. 5x5 크기의 표를 생성하는 기능
- 주어진 키의 알파벳을 순서대로 표에 넣는다.
- 이 때, 이미 표에 들어간 알파벳은 다시 표에 넣지 않는다.
- 키의 중복되지 않는 알파벳을 모두 표에 넣은 뒤, 표에 담기지 않은 알파벳을 순서대로 표에 넣는다.
- 알파벳을 순서대로 저장하는 배열과, 표에 이미 넣은 알파벳을 체크할 map, 표에 저장된 알파벳의 좌표를 저장할 map을 이용해 구현
2. 메시지를 두 글자로 나누는 기능
- 메시지를 순서대로 두 글자씩 순회하며 vector에 저장
- 두 글자가 같지 않다면 pair를 이용해 두 글자를 저장
- 두 글자가 같다면 첫 번째 글자와 'X'를 pair를 이용해 저장하고, 두 번째 글자부터 남은 메시지를 순회
- 두 글자가 같고 'X'라면 첫 번째 글자와 'Q'를 pair를 이용해 저장하고, 두 번째 글자부터 남은 메시지를 순회
- 마지막 글자가 두 글자가 아니라면 첫 번째 글자와 'X'를 pair를 이용해 저장
3. 메시지를 암호화하는 기능
- 두 글자씩 나누어진 메시지와 표에 저장된 알파벳의 좌표를 저장한 map을 이용해 문제에서 주어진 암호화 구현
[ 회고 ]
구현 계획과 검증을 확실히 하지 않아 오류가 발생했다. 두 번째 글자를 'X' 또는 'Q'로 변환할 때, 마지막 글자는 항상 'X'로 변환되어야 하지만 코드의 순서를 신경쓰지 못해 정답을 맞추지 못했다.
구현 계획과 검증 단계에 신경쓰도록 노력해야 할 것이다.
[ 정답 코드 ]
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
vector<char> temp(25);
vector<vector<char>> board(5, vector<char>(5));
vector<pair<char, char>> pairs;
vector<char> alp = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
map<char, int> exist;
map<char, pair<int, int>> cords;
string key;
string msg;
string res = "";
void init() {
cin >> msg >> key;
int k = 0; int a = 0; auto it = temp.begin();
for(; it != temp.end(); it++) {
while (k < key.size() && exist[key[k]]) {
k++;
}
if(k < key.size()) {
*it = key[k];
exist[key[k]]++;
} else break;
}
for(; it != temp.end(); it++) {
while (a < alp.size() && exist[alp[a]]) {
a++;
}
*it = alp[a];
exist[alp[a]]++;
}
int t = 0;
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
board[i][j] = temp[t++];
cords[board[i][j]] = {i, j};
}
}
}
void makePairs() {
for(int i = 0; i < msg.size(); i+=2) {
pair<char, char> p;
p.first = msg[i];
if(i+1 < msg.size()) {
p.second = msg[i+1];
} else {
p.second = 'X';
}
if(p.first == p.second) {
if(p.first == 'X' && i+1 < msg.size()) {
p.second = 'Q';
} else {
p.second = 'X';
}
i--;
}
pairs.push_back(p);
}
}
void encode() {
for(int i = 0; i < pairs.size(); i++) {
int fx = cords[pairs[i].first].first;
int sx = cords[pairs[i].second].first;
int fy = cords[pairs[i].first].second;
int sy = cords[pairs[i].second].second;
if(fx == sx) {
pairs[i].first = board[fx][(fy+1)%5];
pairs[i].second = board[sx][(sy+1)%5];
} else if(fy == sy) {
pairs[i].first = board[(fx+1)%5][fy];
pairs[i].second = board[(sx+1)%5][sy];
} else {
pairs[i].first = board[fx][sy];
pairs[i].second = board[sx][fy];
}
}
}
void solve() {
for(auto pair : pairs) {
res += pair.first;
res += pair.second;
}
}
int main(int argc, char** argv)
{
iostream::sync_with_stdio(0);
cin.tie(0);
init();
makePairs();
encode();
solve();
cout << res << '\n';
return 0;
}
'알고리즘 문제 풀이 > Softeer' 카테고리의 다른 글
[ 소프티어 ] 슈퍼컴퓨터 클러스터 (C++) (1) | 2024.03.27 |
---|---|
[ 소프티어 ] 교차로 (C++) (2) | 2024.02.05 |
[ 소프티어 ] 성적 평가 (C++) (2) | 2024.02.01 |
[ 소프티어 ] 업무 처리 (C++) (0) | 2024.02.01 |
[ 소프티어 ] 출퇴근길 (C++) (1) | 2024.01.31 |