2022.02.05 [백준] C# 나이순 정렬
https://www.acmicpc.net/problem/10814
10814번: 나이순 정렬
온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을
www.acmicpc.net
풀이
위의 문제를 풀기 위해 OrderBy를 사용하였지만 틀렸다는 결과가 나와서 어떻게 해야하나 구글링 중 IComparable을 상속받아 CompareTo를 구현하는 코드를 보게 되었고 최대한 이해하려고 한 후 따라치는 방식으로 코드를 작성했다. 근데 다 작성하고도 반도 이해가 가지 않는 기분이다... 정답 코드는 아래의 블로그에서 참고하면서 작성했습니다.
https://programming-mr.tistory.com/50
백준#10814 - 나이순 정렬
https://www.acmicpc.net/problem/10814 10814번: 나이순 정렬 온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한
programming-mr.tistory.com
https://programming-mr.tistory.com/46
C# List Sort예제.
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69..
programming-mr.tistory.com
Register라는 클래스 정의 후 IComparable을 상속받아 CompareTo를 구현했습니다.
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
44
45
46
47
48
49
50
51
52
53
54
55
56
|
using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Generic;
class Program
{
public class Register : IComparable
{
public static int Indexer;
public int Age;
public int Index;
public string Name;
public Register(int age, string name)
{
this.Age = age;
this.Name = name;
this.Index = Register.Indexer++;
}
public int CompareTo(object obj)
{
Register other = obj as Register;
if (this.Age == other.Age)
{
return this.Index.CompareTo(other.Index);
}
return this.Age.CompareTo(other.Age);
}
}
static void Main()
{
StreamReader sr = new StreamReader(new BufferedStream(Console.OpenStandardInput()));
StreamWriter sw = new StreamWriter(new BufferedStream(Console.OpenStandardOutput()));
StringBuilder sb = new StringBuilder();
Register.Indexer = 0;
int n = int.Parse(sr.ReadLine());
var list = new List<Register>();
for(int i = 0; i < n; i++)
{
string[] s = sr.ReadLine().Split();
list.Add(new Register(int.Parse(s[0]), s[1]));
}
list.Sort();
foreach(var i in list)
{
sw.WriteLine($"{i.Age} {i.Name}");
}
sr.Close();
sw.Close();
}
}
|
cs |