💌문제
https://www.acmicpc.net/problem/1244
1244번: 스위치 켜고 끄기
첫째 줄에는 스위치 개수가 주어진다. 스위치 개수는 100 이하인 양의 정수이다. 둘째 줄에는 각 스위치의 상태가 주어진다. 켜져 있으면 1, 꺼져있으면 0이라고 표시하고 사이에 빈칸이 하나씩
www.acmicpc.net
💌풀이
구현문제로, 문제에서 요구하는 대로만 구현하면 된다.
학생 수만큼 루프 돌면서 현재 원소가 남학생이라면 스위치 개수만큼 루프를 자기가 받은 수만큼 배수로 증가시켜가면서 전부 스위치를 반대로 바꾼다.
만약 현재 원소가 여학생이라면 post랑 back을 각각 현재 원소의 -1, +1 인덱스로 정의해준다.
그리고 계속 while 루프 돌면서 post랑 back 위치의 스위치 상태가 같아지면 인덱스를 또 -1, +1한다.
while문 안에서의 break 조건은 post랑 back 위치가 범위를 벗어났을 때로 건다.
💌자바 코드
package ch1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
class pro1 {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int[] swit=new int[n+1];
StringTokenizer st=new StringTokenizer(br.readLine());
for(int i=1;i<n+1;i++){
swit[i]=Integer.parseInt(st.nextToken());
}
int studentNum=Integer.parseInt(br.readLine());
int[][] student=new int[studentNum][2];
for(int i=0;i<studentNum;i++){
StringTokenizer s=new StringTokenizer(br.readLine());
student[i][0]=Integer.parseInt(s.nextToken());
student[i][1]=Integer.parseInt(s.nextToken());
}
for(int i=0;i<studentNum;i++){
if (student[i][0]==1){ //남학생이라면
for (int j=student[i][1];j<n+1;j+=student[i][1]){
swit[j]=(swit[j]==0)?1:0;
}
}else{ //여학생이라면
int post=student[i][1]-1;
int back=student[i][1]+1;
swit[student[i][1]]=(swit[student[i][1]])==0?1:0;
while(post!=0&&back!=swit.length){
if(post<=0||back>swit.length)
break;
if (swit[post]==swit[back]){
swit[post]=(swit[post]==0)?1:0;
swit[back]=(swit[back]==0)?1:0;
post--;
back++;
}
else
break;
}
}
}
for(int i=1;i<n+1;i++){
System.out.printf("%d ",swit[i]);
if(i%20==0)
System.out.println();
}
}
}
'알고리즘' 카테고리의 다른 글
[프로그래머스/파이썬(Python)] 미로 탈출 level2 (0) | 2023.02.17 |
---|---|
[백준/자바(JAVA)] 구간 합 구하기5 11660 Silver 1 (0) | 2023.02.13 |
[백준/파이썬(Python), 자바(JAVA)] 회의실 배정1931 Silver1 (0) | 2023.02.10 |
[백준/파이썬(Python), 자바(JAVA)] 동전0 11047 Silver 4 (0) | 2023.02.09 |
[백준/파이썬(Python),자바(JAVA)] 기타줄 1049 Silver 4 (0) | 2023.02.08 |
댓글