문제가 더럽게 만들지 않고 깔끔하게 주어져 가볍게 풀었다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
using namespace std;
int n, m;
int map[51][51];
int nmap[51][51];
int ch[51][51];
int dx[] = { 0,0,-1, -1, -1,0,1,1,1 };
int dy[] = { 0,-1,-1,0,1,1,1,0,-1 };
int d, s;
vector<pair<int, int> > v;
pair<int, int> direction(int x, int y) {
for (int i = 0; i < s; i++) {
int xx = x + dx[d];
int yy = y + dy[d];
if (xx == n+1) xx = 1;
else if (xx == 0) xx = n;
if (yy == n+1) yy = 1;
else if (yy == 0) yy = n;
x = xx;
y = yy;
}
return make_pair(x, y);
}
void make() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (ch[i][j] != 1 && map[i][j] >= 2) {
v.push_back(make_pair(i, j));
map[i][j] -= 2;
}
}
}
}
void bug() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
int cnt=0;
if (ch[i][j] == 1) {
for (int k = 2; k <= 8; k+=2) {
int xx = i + dx[k];
int yy = j + dy[k];
if (xx > n || xx <= 0 || yy > n || yy <= 0) continue;
if (map[xx][yy] >= 1) cnt++;
}
nmap[i][j] = cnt;
}
}
}
//nmap에서 옮겨줭 nmap초기화도 같이!
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (nmap[i][j] != 0) {
map[i][j] += nmap[i][j];
nmap[i][j] = 0;
}
}
}
}
void rain() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (ch[i][j] == 1) map[i][j]++;
}
}
}
void go() {
for (int i = 0; i < v.size(); i++) {
int x1, y1;
tie(x1, y1) = v[i];
tie(x1, y1) = direction(x1, y1);
ch[x1][y1] = 1;
}
}
void f() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << map[i][j] << " ";
}
cout << '\n';
}
cout << '\n';
}
void f2() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << ch[i][j] << " ";
}
cout << '\n';
}
cout << '\n';
}
int main() {
// freopen("in1.txt", "rt", stdin);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> map[i][j];
}
}
v.push_back(make_pair(n - 1, 1));
v.push_back(make_pair(n - 1, 2));
v.push_back(make_pair(n, 1));
v.push_back(make_pair(n, 2));
for (int p = 0; p < m; p++) {
cin >> d >> s;
go();//구름 이동
rain();//비가 내리고 물양 +1
v.clear(); //구름 사라짐
bug();//물이 증가한 칸(ch배열)에 대각선 방향에 물이 있는 만큼 +1
make();//구름이 사라진 칸(ch배열)말고, 물양-2확인 후 , 구름 생성
//ch배열 초기화
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) ch[i][j] = 0;
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (map[i][j] != 0) ans += map[i][j];
}
}
cout << ans << '\n';
return 0;
}