티스토리 뷰

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;
}

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

728x90
반응형
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함