백준 20920 c++

magicdrill·2024년 5월 16일

백준 문제풀이

목록 보기
347/673

백준 20920 c++

map과 다중기준 정렬을 연습할 수 있는 문제다.
처음 입력받을 때는 map에 저장하여 빈도수를 저장하고, 입력결과를 정렬이 가능한 vector형태로 재 저장한다.
이후 복합적인 기준에 따라 vector에 저장된 자료들을 정렬하여 범위출력했다.

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;
/*
* 자주 나오는 단어일수록 앞에 배치
* 나오는 횟수가 동일하면 길수록 앞에 배치
* 나오는 횟수 동일하고 길이도 같다면 알파벳 사전 순으로 앞에 배치
*/
/*
* map<string, int> voca; ,단어 키값, 횟수, 길이?
* 근데 map은 sort함수로 정렬이 안되니까 vector로 다시 정렬...
*/

void input_voca(vector<pair<string, int>> &voca)
{
	map<string, int> input;
	int i, N, M;
	string vocabulary;

	cin >> N >> M;
	for (i = 0; i < N; i++)
	{
		cin >> vocabulary;
		if (vocabulary.length() >= M)
		{
			input[vocabulary]++;
		}
	}
	for (auto j : input)
	{
		voca.push_back({ j.first, j.second });
	}

	return;
}

bool compare(pair<string, int> A, pair<string, int> B)
{
	if (A.second == B.second)//출현빈도가 같다면?
	{
		if (A.first.length() == B.first.length())//길이가 같다면?
		{
			//사전순으로
			return A.first < B.first;
		}
		else
		{
			return A.first.length() > B.first.length();//길이가 긴게 우선
		}
	}
	else
	{
		return A.second > B.second;//출현빈도는 내림차순
	}
}

void find_answer(vector<pair<string, int>> &voca)
{
	sort(voca.begin(), voca.end(), compare);
	for (auto ans : voca)
	{
		cout << ans.first << "\n";
	}
	cout << "\n";

	return;
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	vector<pair<string, int>> voca;

	input_voca(voca);
	find_answer(voca);
	
	return 0;
}

0개의 댓글