백준

[백준] 20920번 영단어 암기는 괴로워 (C++, hash, vector, sort)

해랑쓰 2021. 10. 13. 00:11
728x90
반응형

단어가 들어오면 구조체 형태로 배열에 저장하는데, 배열의 접근 인덱스를 hash에 저장한다

만약 cat이라는 단어가 들어오면 hash['cat']=2 (cat이라는 단어의 배열의 인덱스가 2라는 뜻) 형태로 저장하는 것이다.

 

hash에 해당하는 문자열이 없으면 0을 반환하기 때문에 배열 인덱스 0에는 저장하면 안되서 인덱스는 1부터 시작한다.

 

해당하는 조건에 따라서 정렬해줄때도 배열+1의 위치부터 정렬해주고 출력하면 된다.

 

 

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
using namespace std;
#define endl "\n"

typedef struct st {
	string word;
	int cnt;
}memo;


bool comp(memo a, memo b) {

	if (a.cnt == b.cnt) {
			if (a.word.length() == b.word.length()) {
				return a.word < b.word;
			}
			return a.word.length() > b.word.length();
		}
		return a.cnt > b.cnt;
}


memo memolist[100001];
int pc = 1;

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

	
	unordered_map<string, int> index;
	int n, m;
	cin >> n >> m;
	string temp;
	for (register int i = 0; i < n; i++) {
		cin >> temp;
		if (temp.length() < m)continue;
			if(!index[temp]){
				index[temp] = pc;
				memolist[pc].word = temp;
				memolist[pc].cnt = 1;
				pc++;
			}
			else {
				memolist[index[temp]].cnt += 1;
			}
	}

	sort(memolist+1, memolist + pc, comp);
	for (register int i = 1; i < pc; i++) {
		cout << memolist[i].word << endl;
	}
	
	return 0;
}
728x90
반응형