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>
int compare(const void* first, const void* second)
{
int num1 = *(int*)first;
int num2 = *(int*)second;
if (num1 < num2) return -1;
else if (num1 > num2) return 1;
else return 0;
}
int main() {
int n;
scanf("%d", &n);
int* x = (int*)malloc(n * sizeof(int));
int* y = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d %d", &x[i], &y[i]);
}
qsort(x, n, sizeof(int), compare);
qsort(y, n, sizeof(int), compare);
for (int i = 0; i < n; i++) printf("%d %d\n", x[i], y[i]);
free(x);
free(y);
return 0;
}
문제 이해를 잘못해서 " x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성" 부분을 캐치 못하고 정렬만 했다.
.
.
그렇다면 이제 x를 sort할때 x가 같다면 y도 sort하라는 조건문이 있어야 한다.
하지만 마땅한 방법이 생각나지 않아 서치를 해보니 구조체를 활용한 방법이 나왔다.
구조체 풀이
#include <stdio.h>
#include <stdlib.h>
struct xy {
int x;
int y;
};
int compare(const void* first, const void* second)
{
struct xy num1 = *(struct xy*)first;
struct xy num2 = *(struct xy*)second;
if (num1.x < num2.x) return -1;
else if (num1.x > num2.x) return 1;
else { // num1.x==num2.x
if (num1.y < num2.y) return -1;
else if (num1.y > num2.y)return 1;
}
}
int main() {
int n;
scanf("%d", &n);
struct xy* arr = (struct xy*)malloc(n * sizeof(struct xy));
for (int i = 0; i < n; i++) {
scanf("%d %d", &arr[i].x, &arr[i].y);
}
qsort(arr, n, sizeof(struct xy), compare);
for (int i = 0; i < n; i++) printf("%d %d\n", arr[i].x, arr[i].y);
free(arr);
return 0;
}
'코딩 > 백준 문제 (실버)' 카테고리의 다른 글
[백준/24313/C언어] 알고리즘 수업 - 점근적 표기 1 _ 풀이 (0) | 2023.09.02 |
---|---|
[백준/1181/C언어] 단어 정렬 _ 풀이 (0) | 2023.09.01 |
[백준/25206/C언어] 너의 평점은 _ 풀이 (0) | 2023.08.29 |
[백준/2941/C언어] 크로아티아 알파벳 _ 풀이 (0) | 2023.08.23 |
[백준/2563/C언어] 색종이 _ 풀이 (0) | 2023.08.22 |