[BOJ 알고리즘] 1181 "단어 정렬"
● 문제
- 알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
- 길이가 짧은 것부터
- 길이가 같으면 사전 순으로
● 소스코드
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct word
{
char str[52];
};
word words[20005] = {};
bool compare(word i, word j)
{
if(strlen(i.str) > strlen(j.str))
{
return false;
}
else if(strlen(j.str) > strlen(i.str))
{
return true;
}
else
{
if(strcmp(i.str, j.str) >= 0)
{
return false;
}
else
{
return true;
}
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf(" %s", words[i].str);
}
sort(words,words+n,compare);
for(int i=0; i<n; i++)
{
if(i-1 < 0)
{
printf("%s\n", words[i].str);
continue;
}
else
{
if(strcmp(words[i].str, words[i-1].str) == 0)
{
continue;
}
else
{
printf("%s\n", words[i].str);
}
}
}
return 0;
}
● 풀이
- 특별한 알고리즘은 없다.
- 정렬을 위한 compare 함수를 주어진 규칙에 따라 작성하면 된다.
* www.acmicpc.net/problem/1181
1181번: 단어 정렬
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
www.acmicpc.net
'알고리즘 > BOJ(C++)' 카테고리의 다른 글
[BOJ 알고리즘] 1018 "체스판 다시 칠하기" (0) | 2021.06.05 |
---|---|
[BOJ 알고리즘] 9498 "시험 성적" (0) | 2021.05.18 |
[BOJ 알고리즘] 8958 "OX퀴즈" (0) | 2021.05.18 |
[BOJ 알고리즘] 3052 "나머지" (0) | 2021.05.18 |
[BOJ 알고리즘] 2920 "음계" (0) | 2021.05.18 |
댓글