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

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ›„๋ณดํ‚ค(Level 2)

by dkswnkk 2022. 4. 17.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํ›„๋ณดํ‚ค

[["100","ryan","music","2"],["200","apeach","math","2"],["300","tube","computer","3"],["400","con","computer","4"],["500","muzi","music","3"],["600","apeach","music","2"]] 2

programmers.co.kr

 

ํ’€์ด      

#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
map<string,int> uniqueness_table;
vector<string> uniqueness_vec;
set<string> candidate;


bool cmp(string s1, string s2){
    if(s1.length()!=s2.size()) return s1.length()<s2.length();
    return s1<s2;
}

void combination(int index, vector<vector<string>> relation, vector<int> pick){
    map<string,int>temp;
    for(int i=0; i<relation.size(); i++){
        string inp = "";
        for(int k=0; k<pick.size(); k++) inp += relation[i][pick[k]];
        temp[inp]++;
    }
    
    if(temp.size() == relation.size()){
        string inp = "";
        for(int num:pick) inp += to_string(num);
        uniqueness_table[inp] = 1;
        return;
    }
    for(int i=index+1; i<relation[0].size(); i++){
        pick.push_back(i);
        combination(i, relation, pick);
        pick.pop_back();
    }
}

void minimality_check(){
    candidate.insert(uniqueness_vec[0]);
    
    for(int i=1; i<uniqueness_vec.size(); i++){
        bool flag = true;
        for(auto it = candidate.begin(); it!=candidate.end(); it++){
            int cnt = 0;
            for(int k=0; k<it->length(); k++){
                if(uniqueness_vec[i].find(it->data()[k])!=string::npos) cnt++;
            }
            if(cnt == it->length()) flag = false;
        }
        if(flag) candidate.insert(uniqueness_vec[i]);
    }
}

int solution(vector<vector<string>> relation) {
    for(int i=0; i<relation[0].size(); i++) combination(i, relation, {i});
    
    for(auto it = uniqueness_table.begin(); it!= uniqueness_table.end(); it++) uniqueness_vec.push_back(it->first);
    
    sort(uniqueness_vec.begin(),uniqueness_vec.end(),cmp);
    minimality_check();
    
    return candidate.size();
}

 

ํ’€์ด

๊นŒ๋‹ค๋กœ์› ์Šต๋‹ˆ๋‹ค.. ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฝ‘๋Š” ๊ฒƒ๋„ ๊นŒ๋‹ค๋กœ์› ๊ณ , ํŠนํžˆ ํฌ์†Œ์„ฑ์„ ๊ตฌํ•˜๋Š” ๋ถ€๋ถ„์ด ๊ต‰์žฅํžˆ ๊นŒ๋‹ค๋กœ์› ์Šต๋‹ˆ๋‹ค. ํ’€๊ธด ํ–ˆ๋Š”๋ฐ ๋งค์šฐ ์ฐ์ฐํ•ฉ๋‹ˆ๋‹ค.

๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ํ’€์ด๋ฅผ ๋ณด๋ฉด ๋น„ํŠธ ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€์—ˆ๋˜๋ฐ ์‹œ๊ฐ„์ด ๋‚˜๋ฉด ํ•œ๋ฒˆ ๋‹ค์‹œ ๋ณต๊ธฐ๋ฅผ ํ•ด๋ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ํ’€๊ณ  ๋‚˜๋ฉด ํ•ญ์ƒ ํŒŒ์ด์ฌ์œผ๋กœ ํ‘ผ ์ฝ”๋“œ๋ฅผ ๋ณด๋Š”๋ฐ ๊ฐ„๊ฒฐํ•จ์„ ๋ณด๋ฉด ๊ฐˆ์•„ํƒ€์•ผ ํ•˜๋‚˜ ์‹ถ์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€