본문 바로가기
C#/백준 알고리즘

2022.02.05 [백준] C# 좌표 압축

by ian's coding 2022. 2. 5.
728x90
반응형

 

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

 

18870번: 좌표 압축

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

www.acmicpc.net

 


풀이

이 문제는 각 좌표의 대소 관계에 대한 순위를 메기는 문제인거같다.

아래 정답코드에서 lower bound함수를 사용했다. lower bound함수는 이진탐색(Binary Search)기반의 탐색 방법이다.

이 함수는 num[mid] >= target이면서 num[mid] < target 인 최소값을 찾는다.

이 함수에 대해서는 아래의 블로그를 참고했다. 사용하고도 이해하기가 어려운거같다...

 

 

https://blockdmask.tistory.com/168

 

[탐색] lower_bound, upper_bound

안녕하세요. BlockDMask 입니다. 오늘은  이진탐색과 유사하나 조금 다른 lower_bound 와 upper_bound에 대해 알아보겠습니다. 1. lower_bound lower_bound 란? - 이진탐색(Binary Search)기반의 탐색 방법입..

blockdmask.tistory.com

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
using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Generic;
 
class Program
{
    public static int lower_bound(int[] num, int target, int n)
    {
        int start = 0;
        int end = n-1;
        while (start < end)
        {
            int mid = (start + end) / 2;
            if (num[mid] >= target)
            {
                end = mid;
            }
            else
            {
                start = mid + 1;
            }
        }
        return end;
    }
 
    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());
        string[] s = sr.ReadLine().Split();
        int[] num = new int[n];
        for(int i=0;i<n; i++)
        {
            num[i] = int.Parse(s[i]);
        }
        int[] num_Dis = num.Distinct().ToArray();
        Array.Sort(num_Dis);
        
        foreach(int i in num)
        {
            sb.Append(lower_bound(num_Dis, i, num_Dis.Length) + " ");
        }
        sw.WriteLine(sb.ToString());
        sr.Close();
        sw.Close();
    } 
}
cs

 

 

 

 

728x90
반응형

댓글