17144 미세먼지 안녕!
문제 링크
for문을 통해 room행렬을 순환하며 먼지가 있으면 상하좌우를 확인하여 먼지를 퍼뜨렸다. 먼지값 감소값을 room행렬에 저장하고 더할 값은 adder행렬을 만들어 다 퍼트린 후 마지막에 같이 저장하였다.
공기가 순환에 대한 구현이 while문과 if문을 통해 방향전환을 하여 좀 더 많은 연산이 필요해 속도가 느렸다. 이 부분은 그냥 for문으로 단순 이동만 하여 계산속도를 좀 더 빠르게 하는 편이 좋았던 것 같다.
#include <bits/stdc++.h>
using namespace std;
int R, C, T;
int room[50][50], adder[50][50];
pair<int, int> air1, air2;
pair<int, int> dr1[4] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1}};
pair<int, int> dr2[4] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} };
void spreadDust()
{
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++)
{
if (room[r][c] == -1 || room[r][c] == 0)
continue;
int ad = room[r][c] / 5;
int cnt = 0;
if (!ad)
continue;
for (int d = 0; d < 4; d++)
{
int nr = r + dr1[d].first;
int nc = c + dr1[d].second;
if (nr < 0 || nr >= R || nc < 0 || nc >= C || room[nr][nc] == -1)
continue;
cnt += 1;
adder[nr][nc] += ad;
}
room[r][c] -= ad * cnt;
}
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++)
{
room[r][c] += adder[r][c];
adder[r][c] = 0;
}
}
void airCirculation()
{
int d = 0;
int r = air1.first - 1, c = air1.second, nr, nc;
while (true)
{
nr = r + dr1[d].first;
nc = c + dr1[d].second;
if (nr < 0 || nr >= R || nc < 0 || nc >= C || nr > air1.first)
{
d += 1;
continue;
}
if (room[nr][nc] == -1)
{
room[r][c] = 0;
break;
}
room[r][c] = room[nr][nc];
r = nr;
c = nc;
}
r = air2.first + 1, c = air2.second, d = 0;
while (true)
{
nr = r + dr2[d].first;
nc = c + dr2[d].second;
if (nr < 0 || nr >= R || nc < 0 || nc >= C || nr < air2.first)
{
d += 1;
continue;
}
if (room[nr][nc] == -1)
{
room[r][c] = 0;
break;
}
room[r][c] = room[nr][nc];
r = nr;
c = nc;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> R >> C >> T;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++)
{
cin >> room[r][c];
}
for (int r = 2; r < R; r++)
{
if (room[r][0] == -1)
{
air1 = { r, 0 };
air2 = { r + 1, 0 };
break;
}
}
while (T--)
{
spreadDust();
airCirculation();
}
int ret = 0;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++)
{
ret += room[r][c];
}
ret += 2;
cout << ret << "\n";
}
댓글남기기