11650: 좌표 정렬하기

2022. 5. 21. 00:05C언어/백준

-Class2 : Silver5

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

 

-결과

 

-코드

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int x;
    int y;
} coord;

int compare(const void *a, const void *b)
{
    coord A = *(coord *)a; 
    coord B = *(coord *)b;
    if (A.x > B.x) 
        return 1;
    else if (A.x == B.x) 
    {
        if (A.y > B.y)
            return 1;
        else
            return -1; 
    }
    return -1; // A.x < B.x면 -1
}

int main()
{
    int n, i;
    scanf("%d", &n);
    i = 0;
    coord arr[n]; 
    while (i < n)
    {
        scanf("%d %d", &arr[i].x, &arr[i].y);
   
        i++;
    }
    qsort(arr, n, sizeof(coord), compare); 
    i = 0;
    while (i < n)
    {
        printf("%d %d\n", arr[i].x, arr[i].y); 
        i++;
    }
}

 

-풀이

구조체를 사용하여 x와 y를 배열로 따로 선언한다. compare함수를 선언해서 if문을 이용해서 x좌표와 y좌표를 비교해서 그에 따라 return값을 설정한다.

그리고 main함수에서 구조체형으로 배열을 선언하고 x값과 y값을 설정하고 퀵정렬을 사용한 후 정렬된 배열을 출력하여 해결한다.

 

'C언어 > 백준' 카테고리의 다른 글

1920: 수 찾기  (0) 2022.05.21
11651: 좌표 정렬하기 2  (0) 2022.05.21
10989: 수 정렬하기 3  (0) 2022.05.09
10814: 나이순 정렬  (0) 2022.05.09
7568: 덩치  (0) 2022.05.09