본문 바로가기
Study/Coding Test

[백준] 20920 - 영단어 암기는 괴로워 Python, C/C++

by 들숨날숨흡 2023. 10. 12.
728x90

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

 

20920번: 영단어 암기는 괴로워

첫째 줄에는 영어 지문에 나오는 단어의 개수 $N$과 외울 단어의 길이 기준이 되는 $M$이 공백으로 구분되어 주어진다. ($1 \leq N \leq 100\,000$, $1 \leq M \leq 10$) 둘째 줄부터 $N+1$번째 줄까지 외울 단

www.acmicpc.net

 

(1) Python

import sys

input = sys.stdin.readline

N, M = map(int, input().split(" "))
words = dict()

for i in range(N):
    word = input().rstrip()
    if len(word) >= M:
        if word not in words:
            words[word] = 1
        else:
            words[word] += 1

memory = sorted(words, key = lambda x: (-words[x], -len(x), x))

for i in memory:
    print(i)

(2) C/C++

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
using namespace std;
int n, m;
vector <string> voca;
map<string, int> mp;
string v;
bool compare(string a, string b) {
    if (a.size() == b.size() && mp[a] == mp[b]) {
        return a < b;
    }
    else if (mp[a] == mp[b]) {
        return a.size() > b.size();
    }
    return mp[a] > mp[b];
}

int main() {
    cin.tie(NULL); ios::sync_with_stdio(false);
    cout.tie(NULL);
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        cin >> v;
        if (v.size() < m) continue;
        if (mp.find(v)==mp.end()) {
            mp[v] = 0;
            voca.push_back(v);
        }
        mp[v]++;
    }
    sort(voca.begin(), voca.end(), compare);

    for (int i = 0; i < voca.size(); i++) {
        cout << voca[i] << '\n';
    }
}

 

 

 

 


https://github.com/sumini0516

 

sumini0516 - Overview

sumini0516 has 6 repositories available. Follow their code on GitHub.

github.com

 

728x90