C, C++/๐Ÿฅˆ BOJ

(C++) โ˜…Set/Map Upper-Intermediate I - 1 Solvedโ˜…

metamong 2024. 11. 15.

โ˜… 20920 ์˜๋‹จ์–ด ์•”๊ธฐ๋Š” ๊ดด๋กœ์›Œ โ˜…

//20920
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

int N,M;
string word;
map<string,int> freq;
vector<string> vocas;

bool compare(string a, string b){
    if(freq[a] != freq[b]){
        return freq[a] > freq[b];
    }
    else{
        if(a.size() != b.size()){
            return a.size() > b.size();
        }
        else{
            return a < b;
        }
    }
}

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

    cin >> N >> M;

    while(N--){
        cin >> word;
        if(M<=word.length()){
            if(freq[word]){
                freq[word] += 1;
            }
            else{
                freq[word] = 1;
                vocas.push_back(word);
            }
        }
    }
    
    sort(vocas.begin(), vocas.end(), compare);

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


	return 0;
}

 

๐Ÿง‘๐Ÿป‍๐ŸŽจ ๋‹ค์ค‘ ์ •๋ ฌ ์กฐ๊ฑด์ด๋ผ๋ฉด ์กฐ๊ฑด์˜ ์ˆœ์œ„๋ฅผ 1์ˆœ์œ„ - 2์ˆœ์œ„ - 3์ˆœ์œ„ ๋”ฐ์ ธ์„œ ํ™•์ธ ํ•„์š”. sort()์˜ ์„ธ๋ฒˆ์งธ ์ธ์ž compare() ํ•จ์ˆ˜ ์ž‘์„ฑ ์‹œ ๋จผ์ € ์šฐ์„ ์ˆœ์œ„ 1์ˆœ์œ„ ์ง„ํ–‰. ๊ทธ ๋‹ค์Œ 2์ˆœ์œ„ - 3์ˆœ์œ„ ์ˆœ์œผ๋กœ compare() ํ•จ์ˆ˜ ๋‚ด์šฉ ๋งŒ๋“ ๋‹ค.(a์™€ b๋Š” ๊ณ ์ •. ๋ถ€๋“ฑํ˜ธ์— ๋”ฐ๋ผ ์˜ค๋ฆ„์ฐจ์ˆœ / ๋‚ด๋ฆผ์ฐจ์ˆœ ๊ฒฐ์ •)

 

๐Ÿง‘๐Ÿป‍๐ŸŽจ frequency map๊ณผ vector ๊ฐ€๋ณ€ 1์ฐจ์› ๋ฐฐ์—ด ๊ฐ๊ฐ ๋งŒ๋“ค์–ด์„œ ์ง„ํ–‰.


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

๋Œ“๊ธ€