#include <iostream>
#include <string.h>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#define hash(r, c) ((r) * 2002 + (c))
using namespace std;
int T, N;
unordered_map<int, vector<int>> vst; // 초기화 완료
int ans; // 초기화 완료
struct info{
int r, c, d, k;
};
vector<info> atom;
#define IN(r, c) (0 <= (r) && (r) <= 2001 && 0 <= (c) && (c) <= 2001)
int dr[] = { 1, -1, 0, 0 };
int dc[] = { 0, 0, -1, 1 };
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> T;
for (int tc = 1; tc <= T; ++tc) {
cin >> N;
while (N--) {
int r, c, d, k; cin >> r >> c >> d >> k;
atom.push_back({ r + 1000, c + 1000, d, k });
}
ans = 0;
while(1) {
bool proc = false;
vst.clear();
for(int a = 0; a < atom.size(); ++a){
// 처리 대상 아니면 continue;
if (atom[a].r == -1) continue;
if (!IN(atom[a].r, atom[a].c)) {
atom[a].r = -1; continue;
}
proc = true;
// 이동
atom[a].r += dr[atom[a].d];
atom[a].c += dc[atom[a].d];
// 방문 처리
(*vst.insert({ hash(atom[a].r, atom[a].c), vector<int>() }).first).second.push_back(a);
}
if (proc == false) break;
else
for (auto p : vst) {
if (p.second.size() == 1) continue;
for (auto a : p.second) {
ans += atom[a].k;
}
}
}
cout << '#' << tc << ' ' << ans << '\n';
}
return 0;
}
code/BOJ