BOJ_S3_1244
๐ [S3_1244] ์ค์์น ์ผ๊ณ ๋๊ธฐ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int sw = Integer.parseInt(br.readLine());
int[] arr = new int[sw];
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
// ์ค์์น ๋ฒํธ๊ฐ 1๋ถํฐ ์์ ( ํธ์๋ฅผ ์ํด 0๋ฒ์งธ๋ ๋น์๋๋ค )
for (int i = 0; i < sw; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int stu_cnt = Integer.parseInt(br.readLine());
for (int i = 0; i < stu_cnt; i++) {
st = new StringTokenizer(br.readLine(), " ");
int sex = Integer.parseInt(st.nextToken());
int num = Integer.parseInt(st.nextToken());
// ๋จ์
if (sex == 1) {
for (int z = 0; z < sw; z++) {
if ((z+1) % (num) == 0) {
arr[z] = (arr[z] == 0) ? 1 : 0;
} else {
continue;
}
}
}
// ์ฌ์
else if (sex == 2) {
// ์ฒ์์ ์๊ธฐ์์ ๋ฐ๊ฟ์ฃผ๊ธฐ
arr[num-1] = (arr[num-1] == 0) ? 1 : 0;
int left = num-1 - 1;
int right = num-1 + 1;
// ์ผ,์ค ๊ฐ์ด ๋ค๋ฅด๊ฑฐ๋, ์ผ์ชฝ, ์ค๋ฅธ์ชฝ์ด ๋ฒ์๋ฅผ ๋ฒ์ด๋ ๋ ๋๋ด๊ธฐ
while (true) {
if (left < 0 || right > sw-1 || arr[left] != arr[right] ) {
break;
} else {
arr[left] = (arr[left] == 0) ? 1 : 0;
arr[right] = (arr[right] == 0) ? 1 : 0;
left--;
right++;
}
}
}
}
for (int a = 0; a < sw; a++) {
System.out.print(arr[a] + " ");
if((a+1) % 20 == 0) {
System.out.println();
}
}
}
}
๐ค ๋์ ์๊ฐ
์ผ๋จ ์ผํญ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ์ฌ ์ซ์ ๋ฐ๊ฟ์ฃผ๊ธฐ๋ฅผ ํ์๋ค.
๊ทธ๋ฆฌ๊ณ ๋จ์๋ ๊ฐ๋จํ๊ฒ ๋ฐฐ์ ์ฐพ๊ธฐ๋ก ํ์๊ณ
์ฌ์๋ ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ ๊ฒฝ์ฐ ๋ง๊ณ ๋ฌดํ๋ฃจํ๋ฌธ์ ํตํด ์ผ์ชฝ, ์ค๋ฅธ์ชฝ์ ๋น๊ตํด ์ฃผ์๋ค.
์ฒ์์ ๋ฐฐ์ด์ 1 index๋ถํฐ ์ฃผ์ด์ ํ์๋๋ฐ ๊ณ์ํด์ ๋ฐํ์์๋ฌ(ArrayIndexOutOfBounds)๊ฐ ๋ด๋ค.
๊ทธ๋์ 0 index ๋ถํฐ ์ฃผ๋๊น ๋ฌธ์ ๊ฐ ํด๊ฒฐ๋์๋ค.
์ด ๋ฌธ์ ์์๋ ์๋ฅผ ๋ฐ๊พธ๋ ๊ฒ๋ ๋ฐ๊พธ๋ ๊ฑฐ์ง๋ง ์ค์์น ์์๊ฐ 1๋ถํฐ๋ผ์ ๋ฐฐ์ด๊ณผ ๋งค์นํ๋๊ฒ ๊ฐ์ฅ ํท๊ฐ๋ ธ๋ ๊ฒ ๊ฐ๋ค.