본문 바로가기

Problems & Solutions

1244 스위치 켜고 끄기

https://www.acmicpc.net/problem/1244

 

1244번: 스위치 켜고 끄기

첫째 줄에는 스위치 개수가 주어진다. 스위치 개수는 100 이하인 양의 정수이다. 둘째 줄에는 각 스위치의 상태가 주어진다. 켜져 있으면 1, 꺼져있으면 0이라고 표시하고 사이에 빈칸이 하나씩

www.acmicpc.net

 

자바로 입력받을 때 버퍼리더와 스트링토크나이저를 사용하면 시간이 훨씬 적게 걸린다는 점 알아두고 유용하게 써먹자.

 

package baekjoon;
import java.io.*;
import java.util.StringTokenizer;
public class b1244 {

	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int total = Integer.parseInt(br.readLine());
		int switches[] = new int[total];
		StringTokenizer st = new StringTokenizer(br.readLine());
		for(int i=0; i<total; i++)
			switches[i] = Integer.parseInt(st.nextToken());
		
		int stuNum = Integer.parseInt(br.readLine()); 
		
		for(int i = 0; i < stuNum; i++) {
			st = new StringTokenizer(br.readLine());
			int gen = Integer.parseInt(st.nextToken());
			int num = Integer.parseInt(st.nextToken());
			
			if(gen == 1) {
				for(int k = 0; k < total; k++) {
					if((k+1) % num == 0) switches[k] = switches[k] == 0? 1: 0;
				}
			}
			else {
				switches[num-1] = switches[num-1] == 0? 1: 0;
				for(int k = 1; k < total/2; k++) {
					if((num - 1 + k) >= total || (num -1 -k) < 0) {
						break;
					}
					if(switches[num - 1 - k] == switches[num -1 + k]) {
						switches[num - 1 - k] = switches[num - 1 - k] == 0? 1: 0;
						switches[num - 1 + k] = switches[num - 1 + k] == 0? 1: 0;
					}
					else break; 
				}
			}
		}
		for(int i = 0; i < total; i++) {
			System.out.printf(switches[i] + " ");
			if((i+1) % 20 == 0) System.out.println();
		}

	}

}