백준 알고리즘
<백준 알고리즘> 1181번: 단어 정렬
우현짱짱
2021. 7. 1. 00:11
문제
알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
- 길이가 짧은 것부터
- 길이가 같으면 사전 순으로
입력
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
출력
조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.
예제 입력 1
13 but i wont hesitate no more no more it cannot wait im yours |
예제 출력 1
i im it no but more wait wont yours cannot hesitate |
더보기
Solution
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char temp[20000][51]={'\0', };
void merge(char **str,int start,int end,int mid,int N)
{
int i=start, j=mid+1;
for(int k=start;k<=end;k++)
if(j>end)
strcpy(temp[k],str[i++]);
else if(i>mid)
strcpy(temp[k],str[j++]);
else if(strlen(str[i])<strlen(str[j]) || strlen(str[i])==strlen(str[j])&&strcmp(str[i],str[j])<0)
strcpy(temp[k],str[i++]);
else
strcpy(temp[k],str[j++]);
for(int k=start;k<=end;k++)
strcpy(str[k],temp[k]);
}
void merge_sort(char **str,int start,int end,int N)
{
if(start<end)
{
int mid=(start+end)/2;
merge_sort(str,start,mid,N);
merge_sort(str,mid+1,end,N);
merge(str,start,end,mid,N);
}
}
int main(void)
{
int N;
char **str=NULL;
scanf("%d", &N);
getchar();
str=(char **)malloc(N*sizeof(char *));
for(int n=0;n<N;n++)
str[n]=(char *)calloc(51,sizeof(char));
for(int n=0;n<N;n++)
scanf("%s", str[n]);
merge_sort(str,0,N-1,N);
printf("%s\n", str[0]);
for(int n=1;n<N;n++)
if(strcmp(str[n],str[n-1])!=0)
printf("%s\n", str[n]);
for(int n=0;n<N;n++)
free(str[n]);
free(str);
return 0;
}
728x90