반응형
알고리즘 분류 : 시뮬레이션
T개의 톱니바퀴를 회전시키는 시뮬레이션 문제다. BOJ 14891번 '톱니바퀴'와 유사한 문제이다. 자세한 내용은 이전 문제 참조.
- 톱니바퀴의 수는 T개이다. 최대 1,000개.
- 정답은 12시 방향에 S극(1)이 몇 개 있는지만 세면 된다.
C++ 소스코드
#include <cstdio> int a[1000][8]; int t, k, ans; void rotate(int n, int d) { int t[8]; if (d == 1) { for (int i=0; i<8; i++) { t[(i+1)%8] = a[n][i]; } } else { for (int i=0; i<8; i++) { t[i] = a[n][(i+1)%8]; } } for (int i=0; i<8; i++) { a[n][i] = t[i]; } } void solve() { while (k--) { int n, d; scanf("%d %d", &n, &d); n--; int direct[1000] = {0}; direct[n] = d; int x=n, y=n+1; for (int i=n; i<t-1; i++) { if (a[i][2] != a[i+1][6]) direct[i+1] = -direct[i]; else { y = i; break; } } for (int i=n; i>0; i--) { if (a[i][6] != a[i-1][2]) direct[i-1] = -direct[i]; else { x = i+1; break; } } for (int i=x; i<y; i++) { if (direct[i]) { rotate(i, direct[i]); } } } } int main() { scanf("%d", &t); for (int i=0; i<t; i++) { for (int j=0; j<8; j++) { scanf("%1d", &a[i][j]); } } scanf("%d", &k); solve(); for (int i=0; i<t; i++) { if (a[i][0]) ans += 1; } printf("%d\n", ans); return 0; }
Python 3 소스코드
def rotate(n, d): t = [0]*8 if d == 1: for i in range(8): t[(i+1)%8] = a[n][i] else: for i in range(8): t[i] = a[n][(i+1)%8] for i in range(8): a[n][i] = t[i] def solve(): for _ in range(int(input())): n, d = map(int, input().split()) direct = [0]*t direct[n-1] = d for i in range(n-1, t-1): if a[i][2] != a[i+1][6]: direct[i+1] = -direct[i] else: break for i in range(n-1, 0, -1): if a[i][6] != a[i-1][2]: direct[i-1] = -direct[i] else: break for i in range(t): if direct[i]: rotate(i, direct[i]) t = int(input()) a = [list(input().strip()) for _ in range(t)] solve() ans = 0 for i in range(t): if a[i][0] == '1': ans += 1 print(ans)
참고
반응형