๋ฐฑ์ค 14499
https://www.acmicpc.net/problem/14499
Intuition
๋ฌธ์ ์์ฒด๊ฐ ๊ทธ๋ ๊ฒ ์ดํดํ๊ธฐ ์ด๋ ต์ง ์์์ ์ฃผ์ฌ์๋ฅผ ์ด๋ํ๋ ๊ฒ๋ง ์ ๊ตฌํ๋ฉด ๋๋ค๊ณ ์๊ฐํ๋ค.
Approach
์ด๋๋ฐฉํฅ์ผ๋ก ์์ง์ด๋๋ผ๋ ํน์ ๋ฉด์ด ์๋์ ์์๋ ๋์๋จ๋ถ์ ์ค๋ ๋ฉด์ด ๊ณ ์ ๋ ๊ฒ์ด๋ผ ์๊ฐํ๋๋ฐ ์๋์๋ค. ์ด๊ฑธ๋ก 30๋ถ ๋ ๋ ธ๋ค
top_n์ด ํ๋์ ๋ฐ๋ผ๋ณด๋ ๋ฉด, ns ๊ฐ top_n ๊ธฐ์ค์ผ๋ก ๋ถ์ชฝ์ ์๋ ๋ฉด์ผ๋ก ํ๋ค.
ํน์ ๋ฉด์ ๊ธฐ์ค์ผ๋ก ๋ถ์ชฝ์ ์ด๋ค ๋ฉด์ ์๋์ง์ ๋ฐ๋ผ ๋ ์์ ์ค๋ ๋ฉด์ด ๋ฌ๋ผ์ง๋ฏ๋ก ์ด๋ฅผ ๋ฃ์๋ค.
์๋ฅผ๋ค์ด top_n = 1, ns = 2๋ผ๋ฉด ๋์ชฝ์ผ๋ก ์์ง์ผ๋ top_n์ด 4, 6, 3, 1 ~~ ์ํ์ผ๋ก ๋ณํ๋ค.
// 1 -> 5 4 2 3
// 2 -> 1 4 6 3
// 3 -> 5 1 2 6
// 4 -> 6 2 1 5
// 5 -> 3 6 4 1
// 6 -> 3 2 4 5
์ด๋ฅผ ๋ค์๊ณผ ๊ฐ์ด ๊ณ์ฐํด์ ์ด์ฐจ์ ๋ฐฐ์ด์ ๋ฃ์๋ค. (ns -> ๋์ชฝ์ผ๋ก ๊ฐ๋ ๋์ค๋ ๋ฉด)
๋ถ์ชฝ์ผ๋ก ์์ง์ด๋ฉด top_n = ์ฃผ์ฌ์ ๊ธฐ์ค ns์ ๋ฐ๋์ชฝ ๋ฉด, ns = top_n
๋จ์ชฝ์ผ๋ก ์์ง์ด๋ฉด top_n = ns, ns = top_n์ ๋ฐ๋์ชฝ ๋ฉด
๊ณผ ๊ฐ์ด ๊ณ์ฐํด์ ๋ฃ์ด์คฌ๋ค.
Complexity
- Time complexity : O(K)
- Space complexity : O(NM + a)
Code
#include <iostream>
using namespace std;
int N,M, x, y, K, board[21][21], dice[7], dice_r[7]={0,6,5,4,3,2,1}, dx[5]={0,0,0,-1,1}, dy[5]={0,1,-1,0,0};
int d[7][4] = {
{0,0,0,0},{5,4,2,3}, {1,4,6,3},{5,1,2,6},{6,2,1,5},{3,6,4,1},{3,2,4,5}};
// 1 -> 5 4 2 3
// 2 -> 1 4 6 3
// 3 -> 5 1 2 6
// 4 -> 6 2 1 5
// 5 -> 3 6 4 1
// 6 -> 3 2 4 5
int main(){
//initiate
cin>>N>>M>>x>>y>>K;
for (int i=0; i<N; i++)
for (int j=0; j<M; j++)
cin>>board[i][j];
int top_n = 1, ns = 2;
// ๋์๋ก ์์ง์ด๋ฉด ns ๊ทธ๋๋ก
// ๋ถ์ผ๋ก ์์ง์ด๋ฉด top_n = dice_r[ns], ns = top_n
// ๋จ์ผ๋ก ์์ง์ด๋ฉด top_n = ns, ns = dice_r[top_n]
for (int i=0; i<K; i++) {
int dir; cin>>dir;
int nx = x + dx[dir], ny = y + dy[dir];
if (nx >= N || nx < 0 || ny >= M || ny < 0) continue;
x = nx; y = ny;
if (dir == 3) {
int top_n_tmp = top_n;
top_n = dice_r[ns];
ns = top_n_tmp;
}else if (dir == 4) {
int ns_tmp = ns;
ns = dice_r[top_n];
top_n = ns_tmp;
}else {
for (int i=0; i<4; i++) {
if (top_n == d[ns][i]) {
if (dir == 1) {
i += 1;
i %= 4;
top_n = d[ns][i];
}
if (dir == 2) {
i -= 1;
if (i == -1) i += 4;
top_n = d[ns][i];
}
break;
}
}
}
cout<<dice[top_n]<<endl;
if (board[x][y]) {
dice[dice_r[top_n]] = board[x][y];
board[x][y] = 0;
}else {
board[x][y] = dice[dice_r[top_n]];
}
}
}