728x90
반응형
1181번 문제를 풀기 위해서 문제에서 주어진 정렬 조건을 확인하고, 조건에 맞춰 compare함수를 작성하였습니다. c언어에 내장된 qsort와 문자열 함수를 활용하여 문제를 간단하게 해결할 수 있었습니다. 작성한 코드는 다음과 같습니다.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int N;
typedef struct word {
char word_[55];
int length;
} WORD;
WORD words[20020];
int compare(const void* first, const void* second) {
if ((((WORD*)first)->length) < (((WORD*)second)->length)) {
return -1;
}
else if ((((WORD*)first)->length) > (((WORD*)second)->length)) {
return 1;
}
else if ((((WORD*)first)->length) == (((WORD*)second)->length)) {
if (strcmp((((WORD*)first)->word_), (((WORD*)second)->word_)) > 0) {
return 1;
}
else if (strcmp((((WORD*)first)->word_), (((WORD*)second)->word_)) < 0) {
return -1;
}
else if (strcmp((((WORD*)first)->word_), (((WORD*)second)->word_)) == 0) {
return 0;
}
}
else
return 0;
}
int main(void) {
scanf_s("%d", &N);
for (int i = 0; i < N; i++) {
scanf_s("%s", words[i].word_, 55);
words[i].length = strlen(words[i].word_);
}
qsort(words, N, sizeof(WORD), compare);
printf("%s\n", words[0].word_);
for (int i = 1; i < N; i++) {
if ((strcmp(words[i - 1].word_, words[i].word_) != 0)) {
printf("%s\n", words[i].word_);
}
}
return 0;
}
728x90
반응형
'전공 > Problem Solving' 카테고리의 다른 글
[알고리즘/문제풀이/BOJ 18870번] 좌표 압축 (0) | 2021.06.20 |
---|---|
[알고리즘/문제풀이/BOJ 10814번] 나이 순 정렬 (0) | 2021.06.20 |
[알고리즘/문제풀이/BOJ 11651번] 좌표 정렬하기 2 (0) | 2021.06.19 |
[알고리즘/문제풀이/BOJ 11650번] 좌표 정렬하기 (0) | 2021.06.19 |
[알고리즘/문제풀이/BOJ 1427번] 소트인사이드 (0) | 2021.06.19 |