Algorithm/백준

[백준] 20920 영단어 암기는 괴로워 with C++

nowkoes 2023. 5. 5. 00:00

문제설명


입출력 예제


개념

 주어진 문자열을 빈도수 → 길이순 → 알파벳 순으로 정렬하는 문제다. 자료구조 맵을 이용해 특정 길이 이상의 문자열을 빈도수와 함께 컨테이너에 저장한 후, 주어진 조건에 맞게 정렬하면 문제를 해결할 수 있다.


풀이

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

int main()
{
	ios::sync_with_stdio(false); cin.tie(nullptr);

	int N, M;
	string str;
	map<std::string, int> m;

	cin >> N >> M;

 영단어의 개수 N, 외울 단어의 길이 기준 M, 영단어 문자열 str, 단어를 저장할 컨테이너 m을 초기화한다.

 

	while (N--)
	{
		cin >> str;

		if (str.size() >= M)
			m[str]++;
	}

 str의 길이가 길이 조건을 만족하면 맵에 삽입한다.

 

	vector<pair<string, int>> v(m.begin(), m.end());
	sort(v.begin(), v.end(), [](pair<string,int> const& l, pair<string, int> const& r)
		{
			if (l.second != r.second)
				return l.second > r.second;

			else if (l.first.length() != r.first.length())
				return l.first.length() > r.first.length();

			else
				return l.first < r.first;
		});

	for (auto& val : v)
		cout << val.first << '\n';
}

 람다식을 이용해 빈도수 → 길이수 → 알파벳 순에 맞게 조건을 확인한 후 정렬하여 맵에 있는 키의 값을 꺼내서 출력하면 된다.

 

총합본

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

int main()
{
	ios::sync_with_stdio(false); cin.tie(nullptr);

	int N, M;
	string str;
	map<std::string, int> m;

	cin >> N >> M;

	while (N--)
	{
		cin >> str;

		if (str.size() >= M)
			m[str]++;
	}

	vector<pair<string, int>> v(m.begin(), m.end());
	sort(v.begin(), v.end(), [](pair<string,int> const& l, pair<string, int> const& r)
		{
			if (l.second != r.second)
				return l.second > r.second;

			else if (l.first.length() != r.first.length())
				return l.first.length() > r.first.length();

			else
				return l.first < r.first;
		});

	for (auto& val : v)
		cout << val.first << '\n';
}

 

반응형