๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - [3์ฐจ] ํŒŒ์ผ๋ช… ์ •๋ ฌ(Level 2)

by dkswnkk 2022. 5. 4.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - [3์ฐจ] ํŒŒ์ผ๋ช… ์ •๋ ฌ

ํŒŒ์ผ๋ช… ์ •๋ ฌ ์„ธ ์ฐจ๋ก€์˜ ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ์™€ ๋‘ ์ฐจ๋ก€์˜ ๋ฉด์ ‘์ด๋ผ๋Š” ๊ธฐ๋‚˜๊ธด ๋ธ”๋ผ์ธ๋“œ ๊ณต์ฑ„๋ฅผ ๋ฌด์‚ฌํžˆ ํ†ต๊ณผํ•ด ์นด์นด์˜ค์— ์ž…์‚ฌํ•œ ๋ฌด์ง€๋Š” ํŒŒ์ผ ์ €์žฅ์†Œ ์„œ๋ฒ„ ๊ด€๋ฆฌ๋ฅผ ๋งก๊ฒŒ ๋˜์—ˆ๋‹ค. ์ €์žฅ์†Œ ์„œ๋ฒ„์—๋Š” ํ”„๋กœ๊ทธ๋žจ

programmers.co.kr

 

์ฝ”๋“œ

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

//22:13 ~ 22:50
using namespace std;
struct Detail{
    string head;
    int num;
    string origin;
};
vector<string> answer;
bool cmp(const Detail& d1, const Detail& d2){
    if(d1.head!=d2.head) return d1.head<d2.head;
    else if(d1.num!=d2.num) return d1.num<d2.num;
    return false;
}

Detail divide(string s){
    string head,num,temp;
    Detail detail;
    
    for(int i=0; i<s.length(); i++){
        if(!isdigit(s[i])&&num.empty()) temp+=s[i];
        else{
            if(head.empty()){
                head = temp;
                temp.clear();
                num+=s[i];
            }
            else num+=s[i];
        }
    }
    
    detail.head = head;
    detail.num = stoi(num);
    detail.origin = s;
    return detail;
}
vector<string> solution(vector<string> files) {
    vector<Detail> v;
    
    for(string file:files) v.push_back(divide(file));
    
    for(int i=0; i<v.size(); i++) transform(v[i].head.begin(), v[i].head.end(), v[i].head.begin(),::tolower);
    
    stable_sort(v.begin(),v.end(),cmp);	// ์—ฌ๊ธฐ ๊ทธ๋ƒฅ sortํ•˜๋ฉด ํ‹€๋ฆผ!!
    
    for(int i=0; i<v.size(); i++) answer.push_back(v[i].origin);
    
    return answer;
}

int main(){
    solution({"O00321", "O49qcGPHuRLR5FEfoO00321"});
    for(int i=0; i<answer.size(); i++){
        cout<<answer[i]<<'\n';
    }
}

 

ํ’€์ด(37๋ถ„)

์ด ๋ฌธ์ œ๋ฅผ ํ†ตํ•ด์„œ c++์˜ stable_sort์™€ sort์˜ ์ฐจ์ด์— ๋Œ€ํ•ด์„œ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋ถ„๋ช… ์™„๋ฒฝํ•˜๊ฒŒ ๊ตฌํ˜„ํ–ˆ๋Š”๋ฐ ๊ณ„์† ์˜ค๋‹ต์ด ๋œจ๊ธธ๋ž˜ ์งˆ๋ฌธ ๋ชฉ๋ก์„ ์ฐพ์•„๋ณด๋‹ˆ c++์„ ์‚ฌ์šฉํ•˜๋Š” ์‚ฌ๋žŒ์€ sort๋ฅผ stable_sort๋กœ ๋ฐ”๊ฟ”์ฃผ๋ฉด ํ•ด๊ฒฐ์ด ๋œ๋‹ค๊ณ  ํ•ด์„œ ๋ฐ”๊ฟจ๋Š”๋ฐ ๋ฐ”๋กœ ์ •๋‹ต์ด ๋–ด์Šต๋‹ˆ๋‹ค.

 

sort์™€ stable_sort

์ตœ๊ทผ sort์™€ stable_sort๋ฅผ ์จ๋ณผ์ผ์ด ์žˆ์–ด์„œ ํฌ์ŠคํŒ…ํ•ด๋ด…๋‹ˆ๋‹ค. ์ผ๋ฐ˜์ ์œผ๋กœ sort ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ž์ฃผ ์“ฐ๋Š”๋ฐ, stable_sort ๋ผ๋Š” ๊ฒƒ๋„ ์žˆ๋”๊ตฐ์š”. MSDN์— ๋‚˜์™€์žˆ๋Š” stable_sort์˜ ํŠน์ง•์œผ๋กœ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ณต์žก๋„

gamedevforever.com

์ผ๋ฐ˜์ ์œผ๋กœ ์†๋„ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” sort๊ฐ€ ๋” ๋น ๋ฅด์ง€๋งŒ ๋™์ผํ•œ ์šฐ์„ ์ˆœ์œ„์— ํ•œํ•ด์„œ๋Š” ์ˆœ์„œ๋ฅผ ๋ณด์žฅํ•˜์ง€ ์•Š๋Š”๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๋ฐ˜๋ฉด์— stable_sort๋Š” ๋™์ผํ•œ ์šฐ์„ ์ˆœ์œ„์ผ ๋•Œ ์ˆœ์„œ๋ฅผ ๋ณด์žฅํ•ด์ค€๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

๋Œ“๊ธ€