젊은이의 블로그

[BOJ 2840] 행운의 바퀴 본문

문제풀이

[BOJ 2840] 행운의 바퀴

젊은사람 등장 2024. 10. 1. 10:34

참고자료:

https://velog.io/@yoonuk/%EB%B0%B1%EC%A4%80-2840-%ED%96%89%EC%9A%B4%EC%9D%98-%EB%B0%94%ED%80%B4-Java%EC%9E%90%EB%B0%94

 

[백준] 2840: 행운의 바퀴 (Java)

BOJ 2840: 행운의 바퀴 https://www.acmicpc.net/problem/2840제출한 결과 java.lang.ArrayIndexOutOfBoundsException이 떴다.바퀴에 중복된 문자가 있으면 안된다.바퀴는 시계방향으로 돈다. == 화살

velog.io

https://m.blog.naver.com/ka28/221850826909

 

[JAVA] BufferedReader 와 Bufferedwriter 사용법

BufferedReader :Scanner와 유사. Bufferedwriter :System.out.println();과 유사 둘은 모두 기존에 ...

blog.naver.com

https://koohee.tistory.com/14

 

[JAVA] StringTokenizer 사용법

안녕하세요. 프로나인 입니다. 어제 태풍 바비가 강타를 했는데 다들 큰 피해는 없으셨길 바랍니다. 저는 바람이 엄청 불어서 새벽에 유리창 밀리는 소리에 몇 번이나 깼는지 모르겠네요 하하...

koohee.tistory.com

https://computer-science-student.tistory.com/751

 

[자바, Java] 배열 일괄 초기화 - Arrays.fill()

Java 배열 일괄 초기화 - Arrays.fill() 자바에서 배열의 모든 값을 지정한 값으로 초기화하는 메서드로 Arrays.fill()이 있다. 기존에 아래와 같이 for문을 사용해서 배열의 값을 초기화하지 않고도 간편

computer-science-student.tistory.com

https://m.blog.naver.com/wusemr2/222679108660

 

[Python] 파이썬 입출력 / print() / input() / print() 줄바꿈 없애는 방법 / end='\n' / split()

오늘은 Terminal 에서 간단히 입출력을 할 수 있는 코드에 대해 알아보자. 입력을 구현하기 위해 4가지 방...

blog.naver.com

 

import java.util.*;
import java.io.*;

public class BOJ2840 {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		StringTokenizer st = new StringTokenizer(br.readLine(), " ");
		
		int N = Integer.parseInt(st.nextToken()); //바퀴 칸
		int K = Integer.parseInt(st.nextToken()); //회전 횟수
		
		char[] wheel = new char[N];
		Arrays.fill(wheel, '?');
		
		int pointingIndex=0;
		for(int i=0;i<K;i++){
			st = new StringTokenizer(br.readLine(), " "); //몇 칸을 돌릴까
			int S = Integer.parseInt(st.nextToken()); //돌린 후 무슨 문자를 넣을까
			char C = st.nextToken().charAt(0); //계속 새로운 입력을 받기 때문에 가장 앞에 있는 문자를 입력받음
			
			pointingIndex -= S % N;
			if(pointingIndex<0) {
				pointingIndex+= N;
			}
			
			//1. 근데 그 위치가 다른 문자로 이미 채워져 있는 경우
			if(wheel[pointingIndex] != '?' && wheel[pointingIndex] !=C) {
				//충돌 sign인 !를 출력하고 끝냄
				System.out.println("!");
				return;
			}
			
			wheel[pointingIndex] = C;
		}
		
		//2. 다른 위치에 같은 문자가 있는 경우
		for(int i=0;i<N;i++) {
			for(int j=i+1;j<N;j++) {
				if(wheel[i]==wheel[j] && wheel[i]!='?') {
					System.out.println("!");
					return ;
				}
			}
		}
		
		//3. 검사가 모두 끝났음
		for(int i=0;i<N;i++) {
			sb.append(wheel[(pointingIndex+i)%N]);
			//그냥 index 0번부터 출력이 아니라 현재 pointingIndex에서부터 출력하는 것임
		}
		System.out.println(sb);
	}
}

 

헷갈렸던 부분

Integer.parseInt( )를 사용해 StringTonkenizer을 통해 받은 String을 Int로 변환한다.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 로 입력을 받는게 Scaner(System.in)으로 입력받는 것보다 훨씬 빠르다.
시계방향으로 이동: (현재위치 - 이동 칸 수 S + 바퀴 칸 수 N) % 바퀴 칸 수 N
반시계방향으로 이동: (현재위치 - 이동 칸 수 S) % 바퀴 칸 수 N

 

궁금한 부분

배열을 회전시킬 때 왜
pointingIndex -= S % N;
if(pointingIndex<0) {
pointingIndex+= N;
} 로 적으면 시간 오류가 나오지 않는데
pointingIndex = (pointingIndex - S + N) % N;을 하면 시간초과 오류가 나올까?

 

'문제풀이' 카테고리의 다른 글

BOJ 1260, 1920, 11724, 2343  (0) 2024.11.12
[자료구조와알고리즘with파이썬] ch.5  (0) 2024.10.15