백준 14891 톱니바퀴

안승섭·2022년 4월 15일
0

PS

목록 보기
7/10

BOJ 14891

목표 : 톱니바퀴를 K번 회전시킨 후 점수를 구하자.
조건 : 1 <= K <= 100, 톱니바퀴는 8개의 톱니로 구성되어있다.

해결방안

전형적인 구현문제이다. 회전하는 톱니바퀴에 인접한 톱니바퀴의 좌우가 맞물릴 때 서로 다른 극이라면 해당 톱니바퀴도 반대방향으로 회전한다.

#include<iostream>
#include<queue>
#include<string>
using namespace std;
string gear[4]; // L = 6 ,R = 2
int visit[4];
int N;

void turn(int x, int type){
	string tmp = "";
	if (type == 1){ // 시계방향
		tmp += gear[x][7];
		tmp += gear[x].substr(0,7);
	}
	else{ // 반시계방향
		tmp += gear[x].substr(1,7);
		tmp += gear[x][0];		
	}
	gear[x] = tmp;
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL), cout.tie(NULL);
	for (int i = 0; i < 4; i++){
		cin >> gear[i];
	}
	cin >> N;
	while(N--){
		int M, t;
		cin >> M >> t;
		M--;
		queue<int> Q;
		Q.push(M);
		visit[M] = t;
		while(!Q.empty()){
			int cur = Q.front();
			Q.pop();
			int next = cur-1;
			if (0 <= next && next < 4 && !visit[next] && gear[next][2] != gear[cur][6]){ // 좌우가 맞물린다면 반대방향으로 회전
				visit[next] = -visit[cur];
				Q.push(next);
			}
			next = cur+1;
			if (0 <= next && next < 4 && !visit[next] && gear[next][6] != gear[cur][2]){
				visit[next] = -visit[cur];
				Q.push(next);
			}
		}
		for (int i = 0; i < 4; i++){
			if (visit[i]){
				turn(i,visit[i]);
				visit[i] = 0;
			}
		}		
	}
	int ans = 0;
	for (int i = 0; i < 4; i++){
		if (gear[i][0] == '1'){
			ans += (1 << i);
		}
	}
	cout << ans << "\n";
	return 0;
}

profile
Just Do It!

0개의 댓글