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

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์‹ ๊ณ  ๊ฒฐ๊ณผ ๋ฐ›๊ธฐ(Level 1)

by ์•ˆ์ฃผํ˜• 2022. 4. 8.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์‹ ๊ณ  ๊ฒฐ๊ณผ ๋ฐ›๊ธฐ

๋ฌธ์ œ ์„ค๋ช… ์‹ ์ž…์‚ฌ์› ๋ฌด์ง€๋Š” ๊ฒŒ์‹œํŒ ๋ถˆ๋Ÿ‰ ์ด์šฉ์ž๋ฅผ ์‹ ๊ณ ํ•˜๊ณ  ์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฉ”์ผ๋กœ ๋ฐœ์†กํ•˜๋Š” ์‹œ์Šคํ…œ์„ ๊ฐœ๋ฐœํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค. ๋ฌด์ง€๊ฐ€ ๊ฐœ๋ฐœํ•˜๋ ค๋Š” ์‹œ์Šคํ…œ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฐ ์œ ์ €๋Š” ํ•œ ๋ฒˆ์— ํ•œ ๋ช…์˜

programmers.co.kr

 

์ฝ”๋“œ

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <set>

using namespace std;

struct Info{
    set<string> member;
};

vector<int> solution(vector<string> id_list, vector<string> report, int k) {
    vector<int> answer;
    map<string,set<string>> db;
    map<string,int>reported_cnt;
    map<string,int>memory;
    
    for(string s: report){
        vector<string> report_split;
        istringstream ss(s);
        string stringBuffer;
        while(getline(ss, stringBuffer,' ')){   //๊ณต๋ฐฑ ์Šคํ”Œ๋ฆฟ
            report_split.push_back(stringBuffer);
        }
        string reporter = report_split.front();
        
        for(int i=1; i<report_split.size(); i++){   // report ๊ธฐ๋ก
            db[reporter].insert(report_split[i]);
        }
    }
    
    for(auto it=db.begin(); it!=db.end(); it++){    //์‹ ๊ณ  ๋ช‡๋ฒˆ ๋ฐ›์•˜๋Š”์ง€ ๊ธฐ๋ก
        for(auto it2 = it->second.begin(); it2!=it->second.end(); it2++){
            reported_cnt[*it2]++;
        }
    }
    
    for(auto it=db.begin(); it!=db.end(); it++){    //์‹ ๊ณ  ๋ช‡๋ฒˆ ๋ฐ›์•˜๋Š”์ง€ ๊ธฐ๋ก
        int cnt = 0;
        for(auto it2 = it->second.begin(); it2!=it->second.end(); it2++){
            if(reported_cnt[*it2]>=k) cnt++;
        }
        memory[it->first] = cnt;	// ํ•ด๋‹น ์œ ์ €๊ฐ€ ๋ฉ”์„ธ์ง€๋ฅผ ๋ช‡๊ฐœ ๋ฐ›๋Š”์ง€ ๊ธฐ๋ก
    }
    
    for(int i=0; i<id_list.size(); i++){
        answer.push_back(memory[id_list[i]]);	// ๋ฉค๋ฒ„ ์ˆœ์„œ๋Œ€๋กœ ๋ฉ”์„ธ์ง€ ๊ฐฏ์ˆ˜ ์ €์žฅ
    }
    
    return answer;
}

 

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

์ž…์ถœ๋ ฅ๋ถ€ํ„ฐ ๊ณต๋ฐฑ์„ split ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ฃผ์–ด์•ผ ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— C++๋กœ ํ’€๊ธฐ์— ์ฐธ ์•ผ๋ฐ•ํ–ˆ๋˜ ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.(๋ฌผ๋ก  ์ œ ์‹ค๋ ฅ์ด ์—†๋Š” ๊ฒƒ๋„ ์žˆ๊ฒ ์ง€๋งŒ)

  • c++์—์„œ์˜ string split ๊ธฐ๋Šฅ์„ ๋ฐฐ์› ๊ณ ,
  • c++์—์„œ set์˜ ์›์†Œ๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•ด์„œ๋Š” ํฌ์ธํ„ฐ๋กœ ์ ‘๊ทผํ•ด์•ผ ํ•˜๋Š” ๊ฒƒ๋„ ์•Œ๊ฒŒ ๋˜์—ˆ๋˜ ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€