https://programmers.co.kr/learn/courses/30/lessons/12953

 

코딩테스트 연습 - N개의 최소공배수

두 수의 최소공배수(Least Common Multiple)란 입력된 두 수의 배수 중 공통이 되는 가장 작은 숫자를 의미합니다. 예를 들어 2와 7의 최소공배수는 14가 됩니다. 정의를 확장해서, n개의 수의 최소공배

programmers.co.kr

 

최소공배수(LCM), 최대공약수(GCD) 활용 문제이다.

 

#include<bits/stdc++.h>
using namespace std;

long long gcd(int a, int b){
    long long c;
    while(b != 0){
        c = a % b;
        a = b;
        b = c;
    }
    return a;
}

long long lcm(int a, int b){
    return (a*b) / gcd(a, b);
}
long long solution(vector<int> arr) {
    
    int answer = 1;
    for(int i = 0 ; i < arr.size() ; i++){
        answer = lcm(arr[i], answer);
    }
    
    return answer;
}

https://programmers.co.kr/learn/courses/30/lessons/17677

 

코딩테스트 연습 - [1차] 뉴스 클러스터링

뉴스 클러스터링 여러 언론사에서 쏟아지는 뉴스, 특히 속보성 뉴스를 보면 비슷비슷한 제목의 기사가 많아 정작 필요한 기사를 찾기가 어렵다. Daum 뉴스의 개발 업무를 맡게 된 신입사원 튜브

programmers.co.kr

먼저 map을 이용해서 {특정문자열, 존재하는 개수}의 형태로 주어지는 string에 대하여 map을 만들어준다. (코드에서 makeMap 함수)

 

만들기 전에, 대소문자는 구분하지 않는다는 조건을 처리하기 위해서 주어지는 문자열을 모두 소문자로 변환한다.

 

대문자로 변환해도 무관하다.

 

그리고 공집합인 경우를 처리한다.

 

교집합의 경우, 비어있는 map을 생성하고, 한 문자열에 대한 map의 원소가 다른 문자열의 map 원소에 존재하는지 확인하면서, 존재하는 경우에만 새로운 map에 추가해주면 된다.

 

이 때, 교집합에서는 특정원소의 존재하는 개수는 min 값을 사용하기 때문에, 더 작은 값을 넣어주면 된다.

 

합집합의 경우, 특정 문자열의 map에 다른 문자열 map의 원소를 합쳐주면 된다. 따라서 존재하지 않는 경우에는 새롭게 추가해주고, 존재하는 경우에는 더 큰 개수의 값을 넣어주면 된다.

 

#include<bits/stdc++.h>
using namespace std;
map<string, int> mp1, mp2;

map<string, int> makeMap(string str){
    map<string, int> mp;
    
    for(int i = 0 ; i < str.length()-1 ; i++){
        
        // 알파벳 아닌 문자 거르기
        if(!('a' <= str[i] && str[i] <= 'z'))
            continue;
        else if(!('a' <= str[i+1] && str[i+1] <= 'z'))
            continue;
        
        string key = str.substr(i, 2);
        if(mp.find(key) == mp.end()){
            mp.insert({key, 1}); //map에 없으면 추가
        }
        else{
            mp[key]++; //있으면 개수 증가
        }
    }
    return mp;
}
int solution(string str1, string str2) {
    int answer = 0;
    
    // 전부 소문자로 바꾸기
    transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
    transform(str2.begin(), str2.end(), str2.begin(), ::tolower);
    
    mp1 = makeMap(str1); //집합 생성
    mp2 = makeMap(str2);
    
    if(mp1.size() == 0 && mp2.size() == 0){ // 공집합이라 연산 불가능
        return 65536;
    }

    
    int down = 0, up = 0; //분자, 분모
    map<string, int> res; //합집합
    for(auto itr1 = mp1.begin() ; itr1 != mp1.end() ;itr1++){
        string cur = itr1->first;
        
        if(mp2.find(cur) != mp2.end()){
            //있으면(없으면 처리할 게 없음)
            res.insert({cur, min(itr1->second, mp2[cur])});
        }
        up += res[cur];
    }
    
    //교집합
    for(auto itr2 = mp2.begin() ; itr2 != mp2.end() ; itr2++){
        string cur = itr2->first;
        if(mp1.find(cur) != mp1.end()){
            // 있으면
            mp1[cur] = max(itr2->second, mp1[cur]);
        }
        else{
            //없으면
            mp1.insert({cur, itr2->second});
        }
    }
    
    //분모계산(교집합)
    for(auto itr1 = mp1.begin() ; itr1 != mp1.end() ;itr1++){
        down += itr1->second;
    }
       
    answer = up*65536/down;
    return answer;
}

문제 출처:

https://programmers.co.kr/learn/courses/30/lessons/72411

 

코딩테스트 연습 - 메뉴 리뉴얼

레스토랑을 운영하던 스카피는 코로나19로 인한 불경기를 극복하고자 메뉴를 새로 구성하려고 고민하고 있습니다. 기존에는 단품으로만 제공하던 메뉴를 조합해서 코스요리 형태로 재구성해서

programmers.co.kr

 

조합, map을 이용해서 풀이할 수 있다.

코스요리를 이루는 메뉴의 개수가 곧 조합으로 뽑아야 할 개수에 해당하기 때문에, 뽑아주고, 2명이상의 사람에게 가장 많이 뽑힌 메뉴들을 개수별로 벡터에 저장하고, 오름차순으로 사전순 정렬을 해주면 된다.

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <bits/stdc++.h>
using namespace std;
map<stringint> mp;
vector<string> solution(vector<string> ord, vector<int> crs) {
    vector<string> ans;
    for(int i = 0 ; i < crs.size() ; i++){
        int cnt = crs[i];
        for(int j = 0 ; j < ord.size() ; j++){
            
            string curOrd = ord[j];
            sort(curOrd.begin(), curOrd.end());
            if(curOrd.length() < cnt) continue;
            
            vector<int> tmp;
            for(int k = 0 ; k < cnt ; k++){
                tmp.push_back(0);
            }
            for(int k = cnt ; k < curOrd.length() ; k++){
                tmp.push_back(1);
            }
            
            do{
                string str ="";
                for(int k = 0 ; k < curOrd.size() ; k++){
                   
                    if(tmp[k] == 0){
                        str += curOrd[k];
                    }
                }
                if(mp.find(str) == mp.end()){
                    // map에 없으면
                    mp.insert({str, 1});
                }
                else{
                    mp[str]++;
                }
            }while(next_permutation(tmp.begin(), tmp.end()));
        }
        // cur개의 메뉴를 뽑을때, 최대 빈도수로 등장한 메뉴조합
        int maxCnt = 1;
        
        for(auto itr = mp.begin() ; itr != mp.end() ; itr++){
            // cout << itr->first << " = " << itr->second << '\n';
            if(itr->second > maxCnt){
                maxCnt = itr->second;
            }
        }
        if(maxCnt == 1continue;
        for(auto itr = mp.begin() ; itr != mp.end() ; itr++){
            if(itr->second == maxCnt){
                ans.push_back(itr->first);
            }
        }
        mp.clear();
    }
    
    sort(ans.begin(), ans.end());
    return ans;
}
cs

문제 링크는 아래와 같다.

https://www.welcomekakao.com/learn/courses/30/lessons/42579

 

코딩테스트 연습 - 베스트앨범 | 프로그래머스

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가 많이 재생된 장르를 먼저 수록합니다. 장르 내에서 많이 재생된 노래를 먼저 수록합니다. 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다. 노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 play

www.welcomekakao.com

 

 

두 개의 map을 이용했으며, 하나의 map에는 장르별 전체 재생 횟수를 저장했다.

 

또 다른 map에는 key에 장르를, value에 pair 벡터를 저장했다. pair에는 노래의 재생 횟수와 인덱스가 들어가도록 했다.

 

 

map을 구하고 나면, 정렬을 용이하게 하기 위해서 vector를 이용한다.

 

문제의 조건에 따라 정렬 조건을 맞춰주고 답을 구해주면 된다.

 

 

#include <string>
#include <vector>
#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
typedef pair<int, int> pii;

struct Info {
	string str;
	int cnt;
};

bool cmp(pii a, pii b) {
	if (a.first != b.first) 
		return a.first > b.first; //재생 횟수 따라 정렬
	else
		return a.second < b.second; //재생 횟수가 같으면 노래 번호 오름차순으로 정렬
}

bool cmp2(Info a, Info b) {
	return a.cnt > b.cnt; //총 재생 횟수 정렬
}

map<string, vector<pii> > mp; //장르별 노래 재생 횟수
map<string, int> cntMap; //총 재생 횟수

vector<int> solution(vector<string> genres, vector<int> plays) {
	vector<int> answer;

	int songNum = 0;
	for (int i = 0; i < genres.size(); i++) {
		if (mp.find(genres[i]) == mp.end()) {
			vector<pii> tmp;
			tmp.push_back({ plays[i], i }); //i번째 곡이 저만큼 플레이 됨
			mp.insert({ genres[i], tmp });
			cntMap.insert({ genres[i], plays[i] });
		}
		else {
			mp[genres[i]].push_back({ plays[i], i });
			cntMap[genres[i]] += plays[i]; //토탈 추가
		}
	}


	for (auto itr = mp.begin(); itr != mp.end(); itr++) 
		sort(itr->second.begin(), itr->second.end(), cmp); //노래 재생 횟수 내림차순 정렬
	
	

	vector<Info> sortVec; //정렬하기 위해 옮겨담기. <장르, 총재생수>

	for (auto itr = cntMap.begin(); itr != cntMap.end(); itr++) 
		sortVec.push_back({ itr->first, itr->second }); //정렬하기 편하게 벡터에 복사
	
	sort(sortVec.begin(), sortVec.end(), cmp2); //정렬

	for (int i = 0; i < sortVec.size(); i++) {
		string gen = sortVec[i].str;
		answer.push_back(mp.find(gen)->second[0].second);
		if (mp.find(gen)->second.size() > 1) //하나 이상인 경우에만 2번째까지
			answer.push_back(mp.find(gen)->second[1].second);
	}
	return answer;
}

https://www.welcomekakao.com/learn/courses/30/lessons/43163



단어의 철자를 바꿔가면서 목록에 있는 단어들 사이에서 차례로 변화가 일어날 수 있다는 것을 이용해서


인접행렬을 만들어준다.


초기 시작지점을 찾을 때, 단어를 바꾸고 시작하냐, 수정 없이 시작하냐를 따져준다.


목적 단어가 목록에 없으면 BFS를 수행할 필요도 없이 0을 반환해준다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <string>
#include <vector>
#include<iostream>
#include<queue>
using namespace std;
 
int m[51][51], dis[51], st = -1, en = -1;
bool addOne = false;
queue<int> q;
void bfs(vector<string>& grp) {
    q.push(st);
    dis[st]++;
    while (!q.empty()) {
        int qs = q.size();
        while (qs--) {
            int cur = q.front();
            q.pop();
 
            for (int i = 0; i < grp.size(); i++) {
                if (m[cur][i] == 0 || dis[i] >= 0continue;
                q.push(i);
                dis[i] = dis[cur] + 1;
                if (i == en) return;
            }
        }
    }
}
int solution(string src, string dst, vector<string> wrds) {
 
    int len = wrds[0].length();
 
    for (int i = 0; i < wrds.size(); i++) {
        dis[i] = -1;
        if (wrds[i] == src) { //시작 단어와 같은 단어가 목록에 존재
            st = i;
            addOne = false//결과에 1 더해줄 필요가 없음
        }
        if (wrds[i] == dst) en = i;
 
        if (st == -1) { //시작 단어와 같은 단어가 목록에 없는 경우
            int dif = 0;
            for (int k = 0; k < len; k++) {
                if (wrds[i][k] != src[k]) dif++;
                if (dif > 1break;
            }
            if (dif == 1) {
                st = i;
                addOne = true//결과에 1을 더해준다. 시작부터 한번 바꾸고 시작했으니까
            }
        }
 
        //단어를 노드로 인접행렬 만들기
        for (int j = i + 1; j < wrds.size(); j++) {
            int dif = 0;
            for (int k = 0; k < len; k++) {
                if (wrds[i][k] != wrds[j][k]) dif++;
                if (dif > 1break;
            }
            if (dif == 1) { //철자 하나 다를때만 연결
                m[i][j] = 1;
                m[j][i] = 1;
            }
        }
    }
 
    //목표 단어가 목록에 없으면 0 반환
    if (en != -1)
        bfs(wrds);
    else return 0;
 
    if (dis[en] != -1) { //바꿀 수 있으면
        if (!addOne)
            return dis[en];
        else
            return dis[en] + 1;
    }
    else
        return 0;
}
cs


https://www.welcomekakao.com/learn/courses/30/lessons/43162


DFS혹은 BFS를 활용해서 연결되어 있는 정점들의 집합의 수가 몇개인지 구해주면 된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <string>
#include <vector>
 
using namespace std;
bool vis[201];
void dfs(int here, vector<vector<int>> &grp) {
    
    vis[here] = true;
    
    for (int i = 0; i < grp[here].size(); i++) {
        if (grp[here][i] == 0 || vis[i]) continue;
        dfs(i, grp);
    }
}
int solution(int n, vector<vector<int>> coms) {
    
    int ans = 0;
    for (int i = 0; i < coms.size(); i++) {
        if (!vis[i]) {
            ans++;
            dfs(i, coms);
        }
    }
    return ans;
 
    return 1;
}
 
cs


https://www.welcomekakao.com/learn/courses/30/lessons/42842


모든 격자 수의 합이 갈색과 빨간색의 합이 된다.


곱해서 합이 되는 경우를 구하면 카펫의 가로와 세로를 구할 수 있고, 구한 값에 대해서 가운데에


빨간색 격자의 수를 감당할 수 있는지 확인해준다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#pragma warning(disable :4996)
#include<iostream>
#include<vector>
using namespace std;
 
int Sum;
vector<int> solution(int br, int red) {
    vector<int> ans;
 
    Sum = br + red; //전체 격자의 수
    int h; //높이
    for (int w = Sum; w >= 1; w--) {
 
        if (Sum % w == 0) {
            h = Sum / w;
            if (w < h) break//가로가 세로보다 길거나 같을때만 보면됨
            if ((w - 2)*(h - 2== red) {
                ans.push_back(w);
                ans.push_back(h);
            }
        }
    }
    return ans;
}
 
cs


https://www.welcomekakao.com/learn/courses/30/lessons/42841


0이 아닌 숫자를 중복하지 않고 사용해서 세자리 수를 만든다.


세자리 숫자를 만들떄마다, 입력으로 들어오는 스트라이크와 볼 정보를 비교해서 만족하는 수일 경우에만 정답의 수를 증가시켜준다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <string>
#include <vector>
#include<iostream>
#include<set>
using namespace std;
 
bool used[10];
int arr[3];
vector<vector<int> > v; 
int ans = 0;
 
void btk(int k, vector<vector<int> > &clue) {
    if (k == 3) {
        // 후보로 만들어낸 수
        int candi = arr[0* 100 + arr[1* 10 + arr[2];
 
        string candiStr = to_string(candi);
        for (int i = 0; i < clue.size(); i++) {
            int stkCnt = 0, ballCnt = 0;
 
            for (int j = 0; j < candiStr.length(); j++) {
                //char를 int로 바꿔서 비교
                if (candiStr[j] - '0' == v[i][j]) //스트라이크 조건
                    stkCnt++;
                else {
                    for (int m = 0; m < 3; m++) { //볼 조건
                        if (candiStr[j] - '0' == v[i][m])
                            ballCnt++;
                    }
                }
            }
 
            if (stkCnt != clue[i][1|| ballCnt != clue[i][2]) return;
        }
        ans++;
        return;
    }
 
    for (int i = 1; i <= 9; i++) {
        if (!used[i]) {
            arr[k] = i;
            used[i] = true;
            btk(k + 1, clue);
            used[i] = false;
        }
    }
}
 
int solution(vector<vector<int>> clue) {
    vector<int> numlist;
    for (int i = 0; i < clue.size(); i++) {
        int tmp = clue[i][0];
        string strtmp = to_string(tmp);
        //힌트로 들어오는 숫자를 자릿수별로 끊어서 벡터에 저장
        numlist.push_back(stoi(strtmp.substr(01)));
        numlist.push_back(stoi(strtmp.substr(11)));
        numlist.push_back(stoi(strtmp.substr(21)));
        v.push_back(numlist);
        numlist.clear();
    }
 
    btk(0, clue);
    return ans;
}
 
cs


https://www.welcomekakao.com/learn/courses/30/lessons/42839


주어지는 문자열에서, 1개~ 문자열길이만큼 숫자를 뽑아서 수를 만들어보고, 소수라면 set에 담는다.


숫자의 중복을 방지하기 위해서 set을 사용했다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <string>
#include <vector>
#include<iostream>
#include<set>
using namespace std;
 
set<int> candi; //중복 방지를 위해 set 이용
vector<char> v;
bool used[10];
int Sz, arr[8];
 
bool isPrime(int k) {
    if (k == 0 || k == 1return false;
    
    for (int i = 2; i*<= k; i++) {
        if (k % i == 0return false;
    }
    return true;
}
void btk(int k, int cnt, string &nums) {
    if (k == cnt) {
        
        string tmp = "";
        for (int i = 0; i < k; i++
            tmp += nums[arr[i]];
        
        int intTmp = stoi(tmp);
        
        if(isPrime(intTmp)) //만든 숫자가 소수인 경우에만 set에 추가
            candi.insert(intTmp);
    
        return;
    }
    
    for (int i = 0; i < Sz; i++) {
        if (!used[i]) {
            arr[k] = i; //nums의 인덱스를 넣음
            used[i] = true;
            btk(k + 1, cnt, nums);
            used[i] = false;
        }
    }
}
 
int solution(string nums) {
    Sz = nums.length();
    for (int i = 1; i <= nums.length(); i++
        btk(0, i, nums);
    
    return (int)candi.size();
}
 
int main(void) {
    solution("011");
}
cs


주어진 숫자의 개수만큼 연산자를 결정해주면 된다.


첫번째로 결정된 연산자는 첫번째 사용되는 숫자의 부호를 결정한다고 볼 수 있다.


이후의 연산자는 말그대로 연산자로 생각해서 숫자들을 더하거나 빼주는 계산을 해주면 된다.



백트레킹을 통해서 모든 경우의 수에 대하여 연산자를 결정해준다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <string>
#include <vector>
#include<iostream>
 
using namespace std;
int val, opr[2= {1,0}; //+, -
int arr[20], ret = 0;
void btk(int k, vector<int> &nums, int tar) {
    if (k == val) {
        int Sum = 0;
        for (int i = 0; i < k; i++) {
            if (i == 0) { //첫 숫자 부호
                if (arr[0== 1)
                    Sum = nums[0];
                else
                    Sum = nums[0* -1;
            }
            else { //나머지 연산자
                if (arr[i] == 1)
                    Sum += nums[i];
                else
                    Sum -= nums[i];
            }
        }
        if (Sum == tar) ret++;
        return;
    }
    
    for (int i = 0; i < 2; i++) {
        arr[k] = opr[i];
        btk(k + 1, nums, tar);
    }
}
int solution(vector<int> nums, int tar) {
    val = nums.size();
    btk(0, nums, tar);
    return ret;
}
 
int main(void) {
    solution({ 1,1,1,1,1 }, 3);
    return 0;
}
cs


+ Recent posts