반응형
[ 문제 ]
2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
[ 코드 ]
using System.Text;
StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
StringBuilder sb = new StringBuilder();
int n = int.Parse(sr.ReadLine());
int[][] arr = new int[n][];
for (int i = 0; i < n; i++)
{
string[] s = sr.ReadLine().Split();
int x = int.Parse(s[0]);
int y = int.Parse(s[1]);
arr[i] = new int[] { x, y };
}
var result = arr.OrderBy(x => x[0]).ThenBy(y => y[1]).ToArray();
foreach (var item in result)
{
sb.AppendLine($"{item[0]} {item[1]}");
}
sw.Write(sb);
sw.Flush();
sr.Close();
sw.Close();
[ 풀이 ]
n만큼의 2차원 배열을 생성하고 OrderBy로 x좌표를 오름차순 정렬한다. 만약 x좌표가 같은 값이 있을때 y좌표 오름차순으로 정렬을 해야하기때문에 ThenBy를 사용해서 정렬한다.
OrderBy는 중첩 정렬이 안되기때문에 추가 정렬을 할때는 ThenBy를 사용하면 된다.
[ 실행화면 ]
문제링크: 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
반응형
'Language > C#' 카테고리의 다른 글
[C#] 백준 28114번 팀명 정하기 (2) | 2024.02.21 |
---|---|
[C#] 백준 1181번 단어 정렬 (1) | 2024.02.20 |
[C#] 백준 2587번 대표값2 (중앙값을 퀵 정렬 이용하여 풀기) (0) | 2024.02.19 |
[C#] 백준 2839번 설탕 배달 (0) | 2024.02.18 |
[C#] 백준 1436번 영화감독 숌 (0) | 2024.02.17 |