250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 인덱스
- 방어적복사
- transaction
- RDBMS
- ERD
- java
- 이진탐색
- reverse프록시
- proxy
- 정규화
- binarySearch
- 데이터베이스
- 알고리즘
- Database
- 불변객체
- 깊은복사
- 조인
- 자료구조
- acid
- mutable
- forward프록시
- immutable
- index
- NoSQL
- 얕은복사
- 프록시서버
Archives
- Today
- Total
jacketList
10813 공바꾸기 본문
728x90
반응형
1~N번째까지 바구니가 있고 M번 공을 바꾼다 i번과 j번 바구니 공을 바꾸는 작업을하고 바구니 번호를 공백으로 출력한다.
1. Scanner 풀이
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int m = sc.nextInt();
for(int i=0; i<n; i++){
//공의 번호는 바구니의 번호와 같음
arr[i] = i+1;
}
for(int a = 1; a <= m; a++){
int i = sc.nextInt();
int j = sc.nextInt();
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for(int list : arr) {
System.out.print(list + " ");
}
}
}
이렇게 제출했을때 계속 ArrayIndexOutOfBounds 오류가 나왔다 왜?
첫번째 for문을 보면 index가 0 ~ n-1까지이다 그런데 아래 바구니의 index는 입력받은데로 바뀐다. 즉 i-1, j-1 이런식으로 -1을 해줘야 index범위가 같아진다.
2. BufferedReader 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int[] arr = new int[n];
for(int i=0; i<n; i++){
//공의 번호는 바구니의 번호와 같음
arr[i] = i+1;
}
int m = Integer.parseInt(st.nextToken());
for(int a = 0; a < m; a++){
st = new StringTokenizer(br.readLine());
int i = Integer.parseInt(st.nextToken());
int j = Integer.parseInt(st.nextToken());
int temp = arr[i-1];
arr[i-1] = arr[j-1];
arr[j-1] = temp;
}
for(int list : arr) {
System.out.print(list + " ");
}
}
}
728x90
반응형
'알고리즘 > 백준' 카테고리의 다른 글
3052 나머지 (0) | 2023.09.05 |
---|---|
5597 과제 안내신 분..? (0) | 2023.09.03 |
10810 공넣기 (0) | 2023.08.30 |
2562 최댓값 (0) | 2023.08.28 |
10818번 최소, 최대 (0) | 2023.08.28 |