C#/백준 알고리즘

2022.02.05 [백준] C# 좌표 정렬하기 2

ian's coding 2022. 2. 5. 01:15
728x90
반응형

 

 

 

 

 

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

 

11651번: 좌표 정렬하기 2

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

www.acmicpc.net

 


풀이

 

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
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Generic;
 
class Program
{
    
    static void Main()
    {
        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());
        //x,y좌표를 담을 정수배열형 리스트를 선언해준다.
        //※List는 배열형으로도 선언할 수 있음.
        List<int[]> list = new List<int[]>();
        //입력받은 x,y좌표를 list에 추가해줌
        for(int i = 0; i < n; i++)
        {
            string[] s = sr.ReadLine().Split();
            int[] num = new int[2];
            num[0= int.Parse(s[0]);
            num[1= int.Parse(s[1]);
            list.Add(num);
        }
        //list를 OrderBy로 오름차순 정렬할 수 있음.
        //아래의 정렬을 사용하려면 네임스페이스Linq를 사용해야함.
        //내림차순으로 정렬하려면 OrderBy뒤에 Reverse를 하거나
        //OrderBy대신 OrderByDescending()을 사용한다.
        //정렬 조건이 여러개인 경우 OrderBy뒤에 ThenBy를 사용하여 정렬한다.
        var sortList = list.OrderBy(x => x[1]).ThenBy(x=>x[0]);
        foreach(int[] i in sortList)
        {
            sb.Append($"{i[0]} {i[1]}");
            sb.Append("\n");
        }
        sw.WriteLine(sb.ToString());
        sr.Close();
        sw.Close();
    } 
}
cs

 

위 코드에서 사용한 함수는 아래의 링크에서 설명을 볼 수 있음. 

https://lee-ian.tistory.com/125

 

2022.02.05 [백준] C# 좌표 정렬하기

https://www.acmicpc.net/problem/11650 11650번: 좌표 정렬하기 첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 10..

lee-ian.tistory.com

 

 

 

728x90
반응형