각 톱니가 N 또는 S극을 가진 일련의 T개의 톱니바퀴가 주어질 때, 톱니바퀴의 번호와 방향이 주어지면 일련의 톱니바퀴들을 회전시키는 시뮬레이션을 해야한다.
단순 구현 문제입니다.
톱니바퀴와 거의 유사합니다. 하지만 톱니바퀴는 톱니바퀴의 갯수가 4개였지만 이 문제는 최대 1000개까지 주어집니다. 톱니바퀴는 복잡한 분기를 통해서 어떻게든 해결이 가능하지만 이 문제는 재귀를 통해서 구현하는 것이 좋습니다.
과거에 톱니바퀴 문제를 풀었던 코드를 다시 보니까 이 문제를 푼 것보다 더 지저분하고 복잡하게 풀어서 부끄러워집니다.
#include <bits/stdc++.h>
#define VPRT(x, type) copy(x.begin(), x.end(), ostream_iterator<type>(cout, " "))
#define ALL(x) x.begin(), x.end()
#define FASTIO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define endl '\n'
#define MAX 1001
#define R 2
#define L 6
using namespace std;
int t;
deque<bool> dq[MAX];
void rotate(int idx, bool dir)
{
if (dir)
{
dq[idx].push_front(dq[idx].back());
dq[idx].pop_back();
}
else
{
dq[idx].push_back(dq[idx].front());
dq[idx].pop_front();
}
}
void left(int idx, int dir)
{
if (idx != 1 && dq[idx][L] != dq[idx - 1][R])
left(idx - 1, !dir);
rotate(idx, dir);
}
void right(int idx, int dir)
{
if (idx != t && dq[idx][R] != dq[idx + 1][L])
right(idx + 1, !dir);
rotate(idx, dir);
}
int main(void)
{
FASTIO;
cin >> t;
for (int i = 1; i <= t; i++)
{
string str;
cin >> str;
for (auto& j : str)
dq[i].push_back(j == '1' ? true : false);
}
int k;
cin >> k;
while (k--)
{
int idx, dir;
cin >> idx >> dir;
bool d = (dir == 1 ? true : false);
if (t == 1)
{
rotate(1, d);
continue;
}
if (idx == 1)
{
if (dq[idx][R] != dq[idx + 1][L])
right(idx + 1, !d);
rotate(idx, d);
}
else if (idx == t)
{
if (dq[idx][L] != dq[idx - 1][R])
left(idx - 1, !d);
rotate(idx, d);
}
else
{
if (dq[idx][R] != dq[idx + 1][L])
right(idx + 1, !d);
if (dq[idx][L] != dq[idx - 1][R])
left(idx - 1, !d);
rotate(idx, d);
}
}
int res = 0;
for (int i = 1; i <= t; i++)
if (dq[i][0])
res++;
cout << res << endl;
return 0;
}