문제

알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.

  1. 길이가 짧은 것부터
  2. 길이가 같으면 사전 순으로

단, 중복된 단어는 하나만 남기고 제거해야 한다.

풀이

  1. 정렬 함수 제작
    1. 길이가 짧은 순 정렬 함수
      1. 길이가 같으면 사전 순 정렬 함수 호출
      2. 퀵 정렬
    2. 사전순 정렬

image.png

코드

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

#define MAX_WORD_SIZE 51

struct Word{
    char word[MAX_WORD_SIZE];
};

int directionary_sort(const struct Word* a, const struct Word* b){
    return strcmp(a->word, b->word); 
}

int length_sort(const struct Word* a, const struct Word* b){
    int c = strlen(a->word) - strlen(b->word);
    if(c == 0){
        return directionary_sort(a, b);
    }
    else{
        return c;
    }
}

int main() {
    int n;
    scanf("%d", &n);
    struct Word *w = (struct Word *)malloc(sizeof(struct Word) * n);
    for(int i = 0 ; i < n; i++){
        scanf("%s", w[i].word);
    }

    qsort(w, n, sizeof(struct Word), (int(*)(const void*, const void*))length_sort);

    printf("%s\\n", w[0].word);
    for(int i = 1; i < n; i++){
        if(strcmp(w[i].word, w[i-1].word) != 0) {
            printf("%s\\n", w[i].word);
        }
    }

    free(w); 
    return 0;
}