Notice
Recent Posts
Recent Comments
-
[삼성SW테스트] 백준 3190번 - 뱀 (정답률 32%) 본문
https://www.acmicpc.net/problem/3190
삼성 SW테스트 기출 문제다. (유형: 시뮬레이션)
뱀의 머리와 꼬리에 대한 조작이 필요한 시뮬레이션 문제다. 이렇게 양 방향으로 입력/삭제가 필요할 때는 'deque'자료구조가 용이하다.
나는 뱀의 몸(머리/꼬리포함)이 놓여있는 위치를 저장하기 위해 deque<pair<int, int> > snake를 사용하였고,
방향 전환에 대한 조작을 위해 queue<pair<int, char> > turn 를 선언했다.
또, 사과가 놓여있는 장소와 몸이 놓여있는 여부를 표시하기 위해 vector<vector<bool> > check, apple을 선언했다.
주어진 문제의 순서에 맞게 그대로 정확하게 구현하는 것이 중요했다.
그리고 정말 중요한 것은, 방향 전환에 대한 큐에 저장된 가장 마지막의 시간보다 더 늦게 끝날 경우를 대비해 처리해주는 것이었다. ( 60번째 줄의 turn.size() ).
아래는 전체 소스코드. (0ms)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
#include <iostream>
#include <deque>
#include <queue>
#include <vector>
#define MAX 101
using namespace std;
typedef struct dir{
int dr, dc;
}dir;
dir direction[4] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; // 동, 남, 서, 북
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
vector<vector<bool> > check, apple;
deque<pair<int, int> > snake;
queue<pair<int, char> > turn;
int N, K;
cin >> N >> K;
for (int k = 0; k < K; k++){
int a_r, a_c;
cin >> a_r >> a_c;
apple[a_r][a_c] = true;
}
int L;
cin >> L;
for (int l = 0; l < L; l++){
int when;
char toWhere;
cin >> when >> toWhere;
}
int sec = 0; // 초기 시간.
int curdir = 0; // 초기 방향.
check[1][1] = true; // 초기 위치 체크.
snake.push_front(make_pair(1, 1)); // 초기 머리 위치. // 머리는 front, 꼬리는 뒤에.
while (1){
// 다음 시간 시작.
sec++;
// 다음 머리 위치 계산
int cur_head_r = snake.front().first;
int cur_head_c = snake.front().second;
int nr = cur_head_r + direction[curdir].dr;
int nc = cur_head_c + direction[curdir].dc;
// 머리 위치에 따른 계속여부 결정
if (nr < 1 || nc < 1 || nr > N || nc > N || check[nr][nc])
break;
// 계속해도 괜찮으면 다음 머리위치를 snake에 넣고, check해주자.
snake.push_front(make_pair(nr, nc));
check[nr][nc] = true;
// 머리가 이동한 곳에 사과가 있으면 먹어 없애주고,
if (apple[nr][nc])
apple[nr][nc] = false;
// 사과가 없으면 꼬리를 당겨오자.
else{
snake.pop_back();
}
// 여전히 방향 바꿀 것이 있고, 입력해둔 시간에 도달했을 때.
if (turn.size() && sec == turn.front().first){
if (turn.front().second == 'D'){
curdir = (curdir + 1) % 4;
}
else if (turn.front().second == 'L'){
if (curdir == 0) curdir = 3;
else curdir -= 1;
}
turn.pop();
}
}
cout << sec << '\n';
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
'1-1. 삼성 SW 테스트' 카테고리의 다른 글
[삼성SW테스트] 백준 13460번 - 구슬 탈출 2 (정답률 24%) (0) | 2020.01.15 |
---|---|
[삼성SW테스트] 백준 12100번 - 2048 (Easy) (정답률 23%) (0) | 2020.01.15 |
[삼성SW테스트] 백준 13458번 - 시험 감독 (정답률 25%) (0) | 2020.01.14 |
[삼성SW테스트] 백준 14499번 - 주사위 굴리기 (정답률 40%) (0) | 2020.01.14 |
[삼성SW테스트] 백준 14500번 - 테트로미노 (정답률 33%) (0) | 2020.01.13 |
Comments