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

 

2477번: 참외밭

첫 번째 줄에 1m2의 넓이에 자라는 참외의 개수를 나타내는 양의 정수 K (1 ≤ K ≤ 20)가 주어진다. 참외밭을 나타내는 육각형의 임의의 한 꼭짓점에서 출발하여 반시계방향으로 둘레를 돌면서 지

www.acmicpc.net

 


풀이 

처음에는 간단하게 생각해서 ( 전체 큰 사각형 - 작은 사각형 ) 빼면 되는 쉬운 문제 인줄 알았으나 생각보다 시간이 오래 걸렸다. 

큰 사각형 = (가장 큰 세로 X 가장 큰 가로)
작은 사각형 = (가장 작은 세로 X 가장 작은 가로)
Result = 큰 사각형 - 작은 사각형  
이렇게 생각했으나 작은 사각형의 가로,세로값이 가장 작지 않을 수도 있는 경우를 생각하지 못해서 다른 방법을 찾았다.

방법은, 접한 (가로, 세로)의 쌍을 곱해서 모두 더하는 것  

빨간색 사각형은 3번씩, 파란색 사각형 2번씩 더해진다. (x = 빨간색, y = 파란색)
3x + 2y = 22800 (160*50 + 160*30 + 30*20 + 20*60 + 20*100 + 50*160)     // 인접한 가로*세로의 합
x + y = 160*50 = 8000 // 큰사각형 전체의 넓이
비례식을 이용하여 풀이하면 

즉, (인접한 가로*세로 값들의 합 - 가장 큰 사각형의 넓이 X 2) * K

( 22800 - 8000 * 2 ) * 7 = 47600 

※ 여기서 가장 큰 사각형의 넓이는 코드에서 인접한 사각형끼리 곱했을 때 나오는 최댓값을 갱신 하여 구하였다.


 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] agrs) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		int sum = 0;
		int max = Integer.MIN_VALUE;
		int K = Integer.parseInt(st.nextToken());

		st = new StringTokenizer(br.readLine());
		st.nextToken();

		int first = Integer.parseInt(st.nextToken());
		int pre = first;

		for (int i = 1; i < 6; i++) {
			st = new StringTokenizer(br.readLine());
			st.nextToken();
			int cur = Integer.parseInt(st.nextToken());
			max = Math.max(cur * pre, max);
			sum += cur * pre;
			pre = cur;
		}
		max = Math.max(pre * first, max);
		sum += pre * first;
		System.out.println((sum - max * 2)*K);
	}
}

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

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net


동서남북으로 방향이 정해져있던 기존 BFS 와 다르게 나이트의 이동경로 8방향으로 dx,dy 배열을 초기화해주면 되는 간단한 문제이다


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

	static int N, l;
	static int map[][];
	static boolean visited[][];
	static int startX, startY, endX, endY;
	static int dy[] = { -2, -2, -1, -1, 1, 1, 2, 2 };
	static int dx[] = { -1, 1, -2, 2, -2, 2, -1, 1 };

	public static void main(String[] agrs) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		N = Integer.parseInt(br.readLine());

		while (N-- != 0) {
			l = Integer.parseInt(br.readLine());

			map = new int[l][l];
			visited = new boolean[l][l];

			st = new StringTokenizer(br.readLine());

			startY = Integer.parseInt(st.nextToken());
			startX = Integer.parseInt(st.nextToken());

			st = new StringTokenizer(br.readLine());

			endY = Integer.parseInt(st.nextToken());
			endX = Integer.parseInt(st.nextToken());

			System.out.println(BFS(startY, startX));
		}
	}

	static int BFS(int y, int x) {
		
		if (y == endY && x == endX)
			return 0;
		
		Queue<int[]> qu = new LinkedList<int[]>();
		visited[y][x] = true;

		map[y][x] = 0;
		qu.add(new int[] { y, x });

		while (!qu.isEmpty()) {
			int[] temp = qu.poll();

			int curY = temp[0];
			int curX = temp[1];

			if (curY == endY && curX == endX)
				return map[endY][endX];

			for (int k = 0; k < 8; k++) {
				int ny = curY + dy[k];
				int nx = curX + dx[k];

				if (ny < 0 || nx < 0 || l-1 < ny || l-1 < nx)
					continue;

				if (visited[ny][nx])
					continue;

				qu.add(new int[] { ny, nx });
				map[ny][nx] = map[curY][curX] + 1;
				visited[ny][nx] = true;

			}
		}
		return -1;
	}
}

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

 

2206번: 벽 부수고 이동하기

N×M의 행렬로 표현되는 맵이 있다. 맵에서 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다. 당신은 (1, 1)에서 (N, M)의 위치까지 이동하려 하는데, 이때 최단 경로

www.acmicpc.net


BFS의 최단거리를 찾아낸다는 특성을 가지고 풀수 있는 문제지만 벽을 한번 부수고 가야하는 것을 고려해야 하기때문에 생각이 조금 필요한 문제였다.

1. 벽을 부수고 온 경우와 부수고 오지 않은 경우 각각 다른 방문배열에 저장 (3차원 배열)

2.  Class 내에 내부 클래스를 사용하여 필요한 변수를 저장

 

핵심 포인트는 벽을 부수고 가는 경우와 벽을 부수고가지 않는 경우를 모두 고려해야하는데 벽을 부수고 가지 않는 경우가 더 최단거리 일수도 있기때문에  3차원 배열을 사용하여 [0][ny][nx]에 벽을 부수지 않고 방문한 경우, [1][ny][nx]에는 벽을 부수고 방문한 경우, 모두 저장해줘야한다. 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

	static int N, M;
	static boolean visited[][][];
	static int map[][];
	static int dy[] = { 1, 0, -1, 0 };
	static int dx[] = { 0, 1, 0, -1 };

	static class Point {
		int x, y, dis;
		boolean destroyed;

		public Point(int x, int y, int dis, boolean destroyed) {
			this.x = x;
			this.y = y;
			this.dis = dis;
			this.destroyed = destroyed;
		}
	}

	public static void main(String[] agrs) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());

		visited = new boolean[2][N + 1][M + 1];
		map = new int[N + 1][M + 1];

		for (int i = 1; i <= N; i++) {
			String temp = br.readLine();
			for (int j = 1; j <= M; j++) {
				map[i][j] = temp.charAt(j - 1) - '0';
			}
		}

		BFS();

	}

	static void BFS() {
		Queue<Point> qu = new LinkedList<Point>();

		qu.add(new Point(1, 1, 1, false));

		visited[0][1][1] = true;

		while (!qu.isEmpty()) {

			Point curP = qu.poll();

			if (curP.y == N && curP.x == M) {
				System.out.println(curP.dis);
				return;
			}
			
			for (int i = 0; i < 4; i++) {
				int ny = curP.y + dy[i];
				int nx = curP.x + dx[i];

				if (ny <= 0 || nx <= 0 || N < ny || M < nx)
					continue;

				// 벽이 아닌 경우
				if (map[ny][nx] == 0) {
					//지금까지 벽을 부순적인 없는 경우
					if (!curP.destroyed && !visited[0][ny][nx]) {
						qu.add(new Point(nx, ny, curP.dis + 1, false));
						visited[0][ny][nx] = true;
					}
					// 벽을 부수고 온경우
					else if(curP.destroyed && !visited[1][ny][nx]) {
						qu.add(new Point(nx, ny, curP.dis + 1, true));
						visited[1][ny][nx] = true;
					}
				}
				// 벽인 경우
				else {
					// 벽을 부시고 방문한 적이 없으면
					if (!visited[1][ny][nx] && !curP.destroyed) {
						// 벽을 부시고 방문
						qu.add(new Point(nx, ny, curP.dis + 1, true));
						visited[1][ny][nx] = true;
					}
				}
			}

		}

		System.out.println(-1);

	}

}

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

 

1697번: 숨바꼭질

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net


1차원 BFS 를 활용하여 풀수 있는 단순한 문제다.

+1, -1, *2 가 되는 경우를 각각 변수에 저장하여 Queue에 넣어주고

Map 배열에 몇초에 방문할수 있는지 저장하였다.

N = K 인 경우까지 고려하여야 하고, N,K 범위가 0도 가능하다


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

	static int N, K;
	static int cnt = 0;
	static int map[] = new int[100001];

	static Queue<Integer> qu = new LinkedList<Integer>();

	public static void main(String agrs[]) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		N = Integer.parseInt(st.nextToken());
		K = Integer.parseInt(st.nextToken());

		BFS(N);
		System.out.println(map[K]-1);
	}

	static void BFS(int N) {
		qu.add(N);
		map[N] = 1;

		if (N == K)
			return;
		
		
		while (!qu.isEmpty()) {
			int cur = qu.poll();

			if (cur == K)
				break;

			int a = cur + 1;
			int b = cur - 1;
			int c = cur * 2;

			if (0 <= a && a < 100001 && map[a] == 0) {
				qu.add(a);
				map[a] = map[cur]+1;
			}

			if (0 <= b && b < 100001 && map[b] == 0) {
				qu.add(b);
				map[b] = map[cur]+1;
			}

			if (0 <= c && c < 100001 && map[c] == 0) {
				qu.add(c);
				map[c] = map[cur]+1;
			}
		}
	}
}

 

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

 

7569번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,

www.acmicpc.net


7576번 문제의 3차원 배열 버전이다

푸는 방식은 동일하지만, 높이를 고려해야 하기때문에 배열을 3차원으로 선언하여 x,y 뿐만아니라 z까지 이동하는

방법으로 풀었다. static int N , M, H, 을 선언하고 int N, M, H 를 또 선언해줘서 괜한 시간 낭비를 했었다 ..


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

	static int M, N, H;
	static int cnt = 0;
	static int map[][][];
	static int dx[] = { 1, 0, -1, 0, 0, 0 };
	static int dy[] = { 0, 1, 0, -1, 0, 0 };
	static int dz[] = { 0, 0, 0, 0, 1, -1 };
	static boolean visited[][][];
	static Queue<int[]> qu = new LinkedList<int[]>();

	public static void main(String agrs[]) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		M = Integer.parseInt(st.nextToken());
		N = Integer.parseInt(st.nextToken());
		H = Integer.parseInt(st.nextToken());

		map = new int[H + 1][N + 1][M + 1];

		for (int i = 1; i <= H; i++) {
			for (int j = 1; j <= N; j++) {
				st = new StringTokenizer(br.readLine());
				for (int k = 1; k <= M; k++) {
					map[i][j][k] = Integer.parseInt(st.nextToken());

					if (map[i][j][k] == 1) {
						qu.add(new int[] { i, j, k });
					}
				}
			}
		}

		BFS();

		Loop1: for (int i = 1; i <= H; i++) {
			for (int j = 1; j <= N; j++) {
				for (int k = 1; k <= M; k++) {
					cnt = Math.max(map[i][j][k], cnt);

					if (map[i][j][k] == 0) {
						cnt = -1;
						break Loop1;
					}

				}
			}
		}
		if (cnt != -1)
			System.out.println(cnt - 1);
		else 
			System.out.println(cnt);
	
		

	}

	static void BFS() {

		while (!qu.isEmpty()) {
			int curH = qu.peek()[0];
			int curY = qu.peek()[1];
			int curX = qu.peek()[2];

			qu.poll();

			for (int i = 0; i < 6; i++) {
				int nh = curH + dz[i];
				int ny = curY + dy[i];
				int nx = curX + dx[i];

				if (nh <= 0 || ny <= 0 || nx <= 0 || nh > H || ny > N || nx > M)
					continue;

				if (map[nh][ny][nx] != 0)
					continue;

				qu.add(new int[] { nh, ny, nx });

				map[nh][ny][nx] = map[curH][curY][curX] + 1;

			}

		}
	}
}

 

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

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net


기존에 BFS를 돌렸던 방식과 다르게 BFS를 돌릴 Queue 를 static 으로 선언해서

처음부터 익은 토마토가 있으면 순차적으로 Queue 에 넣어서 BFS를 돌리면 해결되는 문제였다.

또한, 전체 토마토가 익지 않은 경우를 생각하기 위해 BFS가 모두 돌았을 때 익지 않은 토마토 (0인 값)이 있으면

-1을 출력하였다.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

	static int M, N;
	static int map[][];
	static int dy[] = { 1, 0, -1, 0 };
	static int dx[] = { 0, 1, 0, -1 };
	static int cnt1 = 0, cnt2 = 0, day = 0;
	static Queue<int[]> qu = new LinkedList<int[]>();

	public static void main(String[] agrs) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		M = Integer.parseInt(st.nextToken()); // 가로
		N = Integer.parseInt(st.nextToken()); // 세로

		map = new int[N + 1][M + 1];

		for (int i = 1; i <= N; i++) {
			st = new StringTokenizer(br.readLine());
			for (int j = 1; j <= M; j++) {
				map[i][j] = Integer.parseInt(st.nextToken());

				if (map[i][j] == 1)
					qu.add(new int[] { i, j });
				else if (map[i][j] == -1)
					cnt1++;
			}
		}

		BFS();

		Loop1: for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= M; j++) {
				day = Math.max(day, map[i][j]);

				if (map[i][j] == 0) {
					day = -1;
					break Loop1;
				}
			}
		}
		if (day != -1)
			System.out.println(day - 1);
		else
			System.out.println(day);
	}

	static void BFS() {

		while (!qu.isEmpty()) {
			int curY = qu.peek()[0];
			int curX = qu.peek()[1];

			qu.poll();

			for (int i = 0; i < 4; i++) {
				int ny = curY + dy[i];
				int nx = curX + dx[i];

				if (ny <= 0 || nx <= 0 || ny > N || nx > M)
					continue;

				if (map[ny][nx] != 0)
					continue;

				qu.add(new int[] { ny, nx });

				map[ny][nx] = map[curY][curX] + 1;

			}
		}

	}
}

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

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어

www.acmicpc.net


간단한 DFS로 해결할수 있는 문제지만 ArrayList 와 Array 두가지 방법을 사용했을 때를 비교하고

두개 다 구현하는 방법을 연습하는 문제로 활용하였다.


Array로 구현한 DFS 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

	static int N, M, V;
	static int map[][];
	static boolean visited[];
	static int cnt =0;

	public static void main(String[] agrs) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		N = Integer.parseInt(br.readLine());
		M = Integer.parseInt(br.readLine());

		map = new int[N + 1][N + 1];
		visited = new boolean[N + 1];

		for (int i = 0; i < M; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());

			int x = Integer.parseInt(st.nextToken());
			int y = Integer.parseInt(st.nextToken());

			map[y][x] = 1;
			map[x][y] = 1;
		}

//		DFS(1);
//
//		Arrays.fill(visited, false);
//		System.out.println();
		
		BFS(1);
		System.out.println(cnt);
	}

	static void DFS(int i) {
		visited[i] = true;
		System.out.print(i + " ");

		for (int j = 1; j < N; j++) {

			if (map[i][j] == 1 && visited[j] == false) {
				visited[j] = true;
				DFS(j);
			}
		}
	}

	static void BFS(int i) {
		Queue<Integer> q = new LinkedList<Integer>();

		q.offer(i);
		visited[i] = true;

		while (!q.isEmpty()) {

			int temp = q.poll();
//			System.out.print(temp + " ");

			for (int j = 1; j <= N; j++) {

				if (map[temp][j] == 1 && visited[j] == false) {
					cnt ++;
					visited[j] = true;
					q.offer(j);
				}
			}
		}
	}
}

ArrayList 로 구현한 DFS 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;

public class Main {

	static ArrayList<ArrayList<Integer>> al = new ArrayList<>();
	static int N, M;
	static boolean[] Visited;

	static int cnt =0;

	public static void main(String[] agrs) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//		StringTokenizer st = new StringTokenizer(br.readLine());

		N = Integer.parseInt(br.readLine());
		M = Integer.parseInt(br.readLine());

		Visited = new boolean[N + 1];

		Arrays.fill(Visited, false);
		for (int i = 0; i <= N; i++) {
			al.add(new ArrayList<Integer>());
		}

		for (int i = 0; i < M; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());

			int x = Integer.parseInt(st.nextToken());
			int y = Integer.parseInt(st.nextToken());

			al.get(x).add(y);
			al.get(y).add(x);
		}

		DFS(1);
		
		System.out.println(cnt-1);
	}

	static void DFS(int V) {
		Visited[V] = true;

		cnt ++;
		for (int i = 0; i < al.get(V).size(); i++) {
			int temp = al.get(V).get(i);

			if (!Visited[temp]) {
				DFS(temp);
			}
		}
	}
}

 


Map 의 기본 개념만 알면 풀수 있는 간단한 문제였다.

오름차순으로 sort_arr 정렬에 재 배치하고

각 정렬된 해당 값을 키값으로 저장한뒤 순서를 value 값으로 Map 에 저장하여

해당 key값에 저장된 value를 가져오는 방법

But,,,, StringBuilder를 쓰지 않을땐 시간초과


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] agrs) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		StringBuilder sb = new StringBuilder();
		int N = Integer.parseInt(br.readLine());
		int[] arr = new int[N];
		int[] sort_arr = new int[N];

		StringTokenizer st = new StringTokenizer(br.readLine());

		for (int i = 0; i < N; i++) {
			arr[i] = Integer.parseInt(st.nextToken());
			sort_arr[i] = arr[i];
		}

		Arrays.sort(sort_arr);

		int n = 0;
		for (int i = 0; i < N; i++) {
			if (!hm.containsKey(sort_arr[i])) {
				hm.put(sort_arr[i], n);
				n++;
			}
		}

		for (int i = 0; i < N; i++) {
			sb.append(hm.get(arr[i]) + " ");
		}
		
		System.out.println(sb);
	}
}

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

 

18870번: 좌표 압축

수직선 위에 N개의 좌표 X1, X2, ..., XN이 있다. 이 좌표에 좌표 압축을 적용하려고 한다. Xi를 좌표 압축한 결과 X'i의 값은 Xi > Xj를 만족하는 서로 다른 좌표의 개수와 같아야 한다. X1, X2, ..., XN에 좌

www.acmicpc.net

 

 


이전문제와 비슷한 문제

익명함수의 개념만 알면 어렵지 않은 문제였다.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] agrs) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int N = Integer.parseInt(br.readLine());

		String[][] arr = new String[N][100];

		for (int i = 0; i < N; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());

			arr[i][0] = st.nextToken();
			arr[i][1] = st.nextToken();
		}

		Arrays.sort(arr, new Comparator<String[]>() {

			@Override
			public int compare(String[] o1, String[] o2) {
				return Integer.parseInt(o1[0]) - Integer.parseInt(o2[0]);
			}

		});

		for (int i = 0; i < N; i++) {
			System.out.println(arr[i][0] + " " + arr[i][1]);
		}

	}

}

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

 

10814번: 나이순 정렬

온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을

www.acmicpc.net

 

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

 

11650번: 좌표 정렬하기

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

www.acmicpc.net


 

문제 로직은 굉장히 단순했지만

람다식에 대한 개념?이 기억이 잘안나서 오래 걸렸던 문제였다.

나중에 다시 공부해야겠다

참고 블로그

https://mangkyu.tistory.com/113

 

[Java] 람다식(Lambda Expression)과 함수형 인터페이스(Functional Interface) - (2/5)

1. 람다식(Lambda Expression) 이란? Stream 연산들은 매개변수로 함수형 인터페이스(Functional Interface)를 받도록 되어있다. 그리고 람다식은 반환값으로 함수형 인터페이스를 반환하고 있다. 그렇기 때문

mangkyu.tistory.com

https://st-lab.tistory.com/243

 

자바 [JAVA] - Comparable 과 Comparator의 이해

아마 이 글을 찾아 오신 분들 대개는 Comparable과 Comparator의 차이가 무엇인지 모르거나 궁금해서 찾아오셨을 것이다. 사실 알고보면 두 개는 그렇게 어렵지 않으나 아무래도 자바를 학습하면서 객

st-lab.tistory.com

https://mangkyu.tistory.com/113

 

[Java] 람다식(Lambda Expression)과 함수형 인터페이스(Functional Interface) - (2/5)

1. 람다식(Lambda Expression) 이란? Stream 연산들은 매개변수로 함수형 인터페이스(Functional Interface)를 받도록 되어있다. 그리고 람다식은 반환값으로 함수형 인터페이스를 반환하고 있다. 그렇기 때문

mangkyu.tistory.com


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
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;

		int N = Integer.parseInt(br.readLine());

		int[][] arr = new int[N][2];

		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine());

			arr[i][0] = Integer.parseInt(st.nextToken());
			arr[i][1] = Integer.parseInt(st.nextToken());
		}

		Arrays.sort(arr, (o1, o2) -> {
			if (o1[0] == o2[0]) {
				return o1[1] - o2[1];
			} else {
				return o1[0] - o2[0];
			}
		});

		for (int i = 0; i < N; i++) {
			System.out.println(arr[i][0] + " " + arr[i][1]);
		}

	}

}

+ Recent posts