< [C++/백준 1181번] 단어 정렬

프로그래밍 공부/백준 (C++)

[C++/백준 1181번] 단어 정렬

Rocketbabydolls 2023. 8. 8. 19:25

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

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

 

 

 

사용한 STL 및 함수

 

vector, sort, unique, erase , c_str()

 

vector : string 값들을 담는 용도로 사용함

sort : 정렬 조건을 설정하고 정렬하는 용도로 사용

unique : 중복 값 제거 , 중복 값이 없는 컨테이너의 마지막 인덱스를 반환한다.

erase : unique 실행 후 남는 쓰레기값들을 지우는 데 활용

c_str() : std::string -> const char* 변환에 사용

 

 

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>

using namespace std;
vector<string> P;

bool cmp(string a, string b)
{
	if (a.length() < b.length())
	{
		return true;
	}
	else if (a.length() > b.length())
	{
		return false;
	}
	else
	{
		if (strcmp(a.c_str(), b.c_str()) < 0)
		{
			return true;
		}
		else if (strcmp(a.c_str(), b.c_str()) > 0)
		{
			return false;
		}
		else
			return false;
	}

}
int main() {
	int N;

	cin >> N;

	for (int i = 0; i < N; i++)
	{
		
		string input;
		
		cin >> input;

		P.push_back(input);

	}

	sort(P.begin(), P.end(), cmp);

	P.erase(unique(P.begin(), P.end()),P.end());

	for (auto i : P)
		cout << i<< "\n";

	return 0;
}