프로그래머스 42628 - 이중우선순위큐

문제 링크

생각 및 접근

  • 이중우선순위큐라고 해서 우선순위 큐를 활용해야 될 것 같았지만, 문제를 분석하다 보니 그냥 vector로 풀어도 상관없겠다는 판단이 났다.
  • operations 돌리기
    • I 숫자라면 vector에 삽입
    • D 1이라면 내림차순으로 나열해서 pop_back()
    • D -1이라면 오름차순으로 나열해서 pop_back()

코드

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

vector<int> solution(vector<string> operations) {
    vector<int> q;
    for(auto o : operations){
        if(o[0] == 'I'){
            string temp = o.substr(2);
            q.push_back(stoi(temp));
        }
        else if(!q.empty() && o == "D 1"){
            if(q.size() != 1)    sort(q.begin(), q.end());
            q.pop_back();
        }
        else if(!q.empty() && o == "D -1"){
            if(q.size() != 1)    sort(q.rbegin(), q.rend());
            q.pop_back();
        }
    }

    sort(q.begin(), q.end());
    vector<int> answer;
    if(q.empty()){
        answer.push_back(0);
        answer.push_back(0);
    }
    else{
        answer.push_back(q[q.size() - 1]);
        answer.push_back(q[0]);
    }
    return answer;
}

채점 결과

프로그래머스 42629 - 라면공장

문제 링크

생각 및 접근

사족

  • 나는 이런 문제에 약한 것 같다. 날짜와 데이터가 섞여서 최적의 결과를 나타내는 문제들. 연습을 좀 해야겠다.

본론

  • dates와 supplies를 묶어서 관리하기 위해 새로운 구조체 Data를 하나 선언한다.

      struct Data{
          int date;
          int supply;
          Data(int a, int b): date(a), supply(b) {}
      };
  • 밀가루를 공급받기 위해 판단의 기준이 되는 우선순위 큐 pq 하나와, 밀가루를 공급받기 위한 날짜의 후보를 넣어두는 큐 q 하나를 선언한다.

    • 우선순위 큐

        priority_queue<Data, vector<Data>, cmp> pq;
    •   queue<Data> q;
        for(int i = 0; i < dates.size(); i++)
            q.push(Data(dates[i], supplies[i]));
  • 후보들은 q에서 대기하고 있다가, pq에 넣어질 수 있는 조건이 충족되면 그때서야 pq에 넣어진다.

    • 조건

      • 내가 가지고 있는 밀가루 양보다 q.front().date가 작아야 한다.

      • why : 공장의 운영이 끊기면 안된다. 밀가루 양 currentcurrent일까지 공장이 운영될 수 있는 날이고, 밀가루는 미리 받아놓거나 (current > q.front().date인 경우) 밀가루가 떨어진 바로 다음날 새벽 (current = q.front().date인 경우) 에 받을 수 있기 때문에, 다음과 같은 식이 성립될 때 pq에 넣을 수 있다.

          current >= q.front().date
  • pq에 넣어진 것들은 supply가 가장 큰 순서대로 나열된다. 이는 밀가루를 greedy하게 골라 다른 날짜에서 밀가루를 또 받는 일을 방지한다.

      struct cmp{
          bool operator()(Data a, Data b){
              return a.supply < b.supply;
          }
      };
  • pq의 top에 있는 것이 공장이 받을 밀가루가 되므로, current += pq.top().supply;

코드

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

struct Data{
    int date;
    int supply;
    Data(int a, int b): date(a), supply(b) {}
};

struct cmp{
    bool operator()(Data a, Data b){
        return a.supply < b.supply;
    }
};

int solution(int stock, vector<int> dates, vector<int> supplies, int k) {
    int answer = 0;
    int current = stock;

    priority_queue<Data, vector<Data>, cmp> pq;
    queue<Data> q;

    for(int i = 0; i < dates.size(); i++)
        q.push(Data(dates[i], supplies[i]));

    while(current < k){
        while(!q.empty() && current >= q.front().date){
            pq.push(q.front());
            q.pop();
        }

        current += pq.top().supply;
        pq.pop();
        answer++;
    }

    return answer;
}

채점 결과

프로그래머스 42626 - 더 맵게

문제 링크

생각 및 접근

  • 스코빌 지수가 제일 낮은 것과 그 다음으로 낮은 것을 찾아야 하므로 처음에는 C++ STL Algorithm의 sort로 해결하려고 했으나, 정렬하고 두 개 뽑아서 하나 넣고, 정렬하고 두 개 뽑아서 하나 넣고 식의 코드는 시간 효율이 너무 떨어질 것 같았다.
  • 그래서 새로 생각해낸 방식이 우선순위 큐 활용하기 (우선순위 큐에 대한 내용 링크)
  • 우선순위 큐를 최소 힙으로 선언하여, 우선순위 큐에 scoville의 값들을 다 넣고, 부모 노드 두개만 뽑아서 값을 체크하면 된다.
  • 답을 반환하는 시점
    • 우선순위 큐의 top이 K보다 크거나 같을 때 (모든 음식의 스코빌 지수를 K 이상으로 만든 경우)
    • 우선순위 큐의 top이 K보다 작고, 그 값이 우선순위 큐에 존재하는 유일한 원소일 때 (모든 음식의 스코빌 지수를 K 이상으로 만들 수 없는 경우)

코드

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

int solution(vector<int> scoville, int K) {
    int answer = 0;

    priority_queue<int, vector<int>, greater<int> > pq;    
    for(auto s : scoville)  pq.push(s);

    while(-1){        
        int low1 = pq.top();
        pq.pop();
        if(low1 >= K)       return answer;
        if(pq.size() == 0)  return -1;

        int low2 = pq.top();
        pq.pop();

        pq.push(low1 + low2 * 2);
        answer++;
    }
}

채점 결과

코딩 테스트 전 Cheating Sheet in C++

본 문서는 코딩 테스트에서 유용하게 사용될 수 있는 STL 등을 잠시 흘겨볼 수 있도록 작성된 문서입니다.
자세한 이론은 링크를 달아두었으니 참고하면 됩니다.

목차

  1. 입출력 속도 향상
  2. 모든 라이브러리를 대체하는 라이브러리
  3. string과 char * , int 의 변환
  4. C++ STL Algorithm의 sort 함수
  5. DFS와 BFS의 포인트
  6. union find algorithm
  7. C++ STL string
  8. C++ STL vector
  9. C++ STL stack
  10. C++ STL queue
  11. C++ STL priority_queue
  12. C++ STL map
  13. min_element, max_element
  14. next_permutation
  15. 입력 끝 판단하기

입출력 속도 향상

  • 링크

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

모든 라이브러리를 대체하는 라이브러리

  • 링크

    #include <bits/stdc++.h>

string과 char * , int 의 변환

  1. char * -> string

     char * cStr = "Cstring";
     string appStr = cStr;
  2. string -> char *

     string cStr = "Cstring";
     const char * cStr2 = cStr.c_str();
     // const 타입으로 리턴되는 것을 기억
  3. char * -> int

     char * cStr = "20200701"
     int num = atoi(cStr);
  4. string -> char * -> int

     string s = "2020"
     int num = atoi(s.c_str());

C++ STL Algorithm의 sort 함수

배열인 경우

  • 오름차순

      int arr[10] = {5, 4, 3, 2, 1, 9, 8, 7, 6, 10};
      sort(arr, arr + 10);
  • 내림차순

      int arr[10] = {5, 4, 3, 2, 1, 9, 8, 7, 6, 10};
      sort(arr, arr + 10, greater<int>());

vector인 경우

  • 오름차순

      sort(v.begin(), v.end());
  • 내림차순

      sort(v.rbegin(), v.rend());

DFS와 BFS의 포인트

DFS

  • DFS 함수의 파라미터로 무엇을 넘기고 넣을 것인가
  • DFS의 초깃값을 어떻게 잡을 것인가
  • 언제 DFS를 멈추게 할 것인가
  • DFS 함수 내에서 새 DFS 함수를 호출할 때 문제의 조건에 맞게 적절히 호출하는가

BFS

  • queue의 데이터 타입
  • queue의 초깃값
  • q.front() 원소가 답이 될 수 있는지, 혹은 정보 update가 가능한지 check 이후 행동
  • 읽어온 원소로부터 queue에 push할 수 있는 원소를 push 하기

C++ STL string

.at

  • 해당 위치에 해당하는 문자를 반환

      String str = "MyName";
      char c = str.at(0); // c = 'M'

.assign

  • 문자열을 할당

  • ( 문자열 ) : 문자열을 할당

  • ( 개수, 문자 ) : 문자를 개수만큼 할당

  • ( 문자열, 시작위치, 개수 ) : 매개변수 문자열의 시작 위치부터 개수만큼을 호출한 문자열에 할당

      string s1, s2, s3;
      s1.assign("ABCDEFG"); // s1 = "ABCDEFG"
      s2.assign(3,'a');     // s2 = "aaa"
      s3.assign(s1,2,4);    // s3 = "CDEF"

.append

  • 문자열을 끝에 더한다

  • ( 문자열 ) : 문자열을 더한다

  • ( 개수, 문자 ) : 문자를 개수만큼 끝에 더한다

  • ( 문자열, 시작위치, 개수 ) : 매개변수 문자열의 시작 위치부터 개수 만큼을 호출한 문자열에 할당

      string s1, s2;
      s1.append("ABCDEF");  // s1 = "ABCDEF"
      s1.append(3,'x');     // s1 = "ABCDEFxxx"
      s2.append(s,2,4);     // s2 = "CDEF"
      s2 += "X";            // s2 = "CDEFX"

.clear

  • 문자열의 내용을 모두 삭제

      s.clear();

.empty

  • 문자열이 비어있는 지 확인

      s.empty();

.substr

  • 문자열의 일부분을 문자열로 반환

  • ( 시작위치 ) : 시작위치부터 끝까지의 문자들을 문자열로 반환

  • ( 시작위치, 개수 ) : 시작위치부터 개수만큼의 문자를 문자열로 반환

      string s = "ABCDEF";
      string s2 = s.substr(4);    // s2 = "EF"    (index 4부터 끝까지의 문자열을 반환)
      string s3 = s.substr(1,3);    // s3 = "BCD" (index 1부터 3까지의 문자열을 반환)

.strstr(char * a, char * b)

  • 문자열 a에 문자열 b가 포함되어 있는지, 즉 부분 문자열인지 확인한다.

  • 없다면 NULL을 리턴함

      #include <bits/stdc++.h>
      using namespace std;
    
      char a[1000001], b[1000001];
    
      int main(){
          ios_base::sync_with_stdio(false);
          cin.tie(NULL);  cout.tie(NULL);
    
          cin >> a >> b;
          if (strstr(a, b) == NULL)   cout << 0;
          else                        cout << 1;
      }

C++ STL vector

vector 생성

  • empty vector 생성

      vector<int> a;
  • size가 정의된 vector 생성

      vector<int> a(5);
  • vector 배열 생성

      vector<int> a[3];
      c[0].push_back(1);
      c[0].push_back(2);
      c[1].push_back(2);
      c[2].push_back(3);
      cout << c[1][0] << endl;
  • pair와 vector를 혼합

      vector< pair<int, int> > graph[3];
      graph[1].push_back({3, 5});
      graph[2].push_back(make_pair(7, 7));
      cout << graph[1][0].first << " " << graph[2][0].second << endl;
  • struct와 vector를 혼합

      struct Data{
          int money;
          int when;
          Data(int a, int b){
              money = a;
              when = b;
          }
          bool operator<(const Data &b) const {
              return when > b.when;
          }    
      };
    
      int main(){
          vector<Data> T;
          // ...
          T.push_back(Data(a, b));
          sort(T.begin(), T.end());
          // ...
      }
  • vector 중복값 없애기

      sort(v.begin(), v.end());
      v.erase(unique(v.begin(),v.end()), v.end());

C++ STL stack

  • 링크
  • stack<int> s;
  • s.push(element); : top에 원소를 추가
  • s.pop(); : top에 있는 원소를 삭제
  • int a = s.top() : top에 있는 원소를 반환
  • s.empty(); : s가 비어있다면 true를, 비어있지 않다면 false
  • s.size(); : s의 크기를 반환

C++ STL queue

  • 링크
  • queue<int> q;
  • q.push(element); : 큐에 원소 push
  • q.pop(); : 큐의 원소 pop
  • int a = q.front(); : 큐 제일 앞에 있는 원소 반환
  • int b = q.back(); : 큐 제일 뒤에 있는 원소 반환
  • q.empty(); : 큐가 비어있으면 true, 비어있지 않다면 false
  • q.size(); : 큐의 원소 갯수 반환

C++ STL priority_queue

최대 힙 (MAX HEAP)

  • 부모 노드가 최댓값

      priority_queue<int, vector<int>, less<int>> pq;

최소 힙 (MIN HEAP)

  • 부모 노드가 최솟값

      priority_queue<int, vector<int>, greater<int>> pq;

우선순위 큐에 사용자 정의 함수 적용하기

struct State{  
int x, y, dis;  
State(int a, int b, int c){  
x = a; y = b; dis = c;  
}  
bool operator < (const State & b) const {  
if(dis == b.dis){  
// prior 3  
if(x = b.x) return y > b.y;  
// prior 2  
else return x > b.x;  
}  
// prior 1  
else return dis > b.dis;  
}  
};

priority\_queue Q;

C++ STL map

map 선언

map<char, int> m;

map의 key로 접근하여 value 바꾸기 / 추가하기

m['c']++;
m['d'] = 7;

map의 모든 원소 출력

// with iterator
map<char, int>::iterator itr;

for(itr = m.begin(); itr != m.end(); itr++){
    cout << itr->first << " " << itr->second << endl;
}

// with auto
for(auto &k : m){
    cout << k.first << " " << k.second << endl;
}

map의 단일 원소 출력

  • 주의 : 개발자가 추가하지 않는 value를 출력하려고 할 때 오류를 반환하지 않고 0을 출력해준다.

      cout << m['c'] << endl;

min_element, max_element

배열에서

int *arr = new int[size];
for(int i = 0; i < size; i++){
    cin >> arr[i];
}
cout << "max : " << *max_element(arr, arr + size) << endl;
cout << "min : " << *min_element(arr, arr + size) << endl;

vector에서

vector<int> v;
for(int i = 0; i < size; i++){
    cin >> val;
    v.push_back(val);
}
cout << "max : " << *max_element(v.begin(), v.end()) << endl;
cout << "min : " << *min_element(v.begin(), v.end()) << endl;
  • 만약 max_element(v.begin() + 2, v.begin() + 5) 라고 사용했다면 v[2]부터 v[4]까지 중 최대값을 찾아준다.

next_permutation

순열 (permutation)

오름차순에서 내림차순으로
sort(v.begin(), v.end());
do{
    // do something
} while(next_permutation(v.begin(), v.end());
내림차순에서 오름차순으로
sort(v.rbegin(), v.rend());
do{
    // do something
} while(next_permutation(v.rbegin(), v.rend());

조합 (combination)

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

int n, r, ch[20];

void dfs(int s, int L){
    if(L == r){
        for(int i = 0; i < r; i++)
            printf("%d ", ch[i]);
        printf("\n");
    }
    else{
        for(int i = s; i < n; i++){
            ch[L] = i;
            dfs(i + 1, L + 1);
        }
    }
}

int main(){
    cin >> n >> r;
    dfs(0, 0);
}
오름차순에서 내림차순으로
#include <bits/stdc++.h>
using namespace std;

int n, r;

int main (){
    cin >> n >> r;
    vector<int> v, ind;
    for(int i = 0; i < n ; i++)
        v.push_back(i);
    for(int i = 0; i < r; i++)
        ind.push_back(0);
    for(int i = 0; i < n - r; i++)
        ind.push_back(1);
    sort(ind.begin(), ind.end());

    do{
        for(int i = 0; i < n; i++){
            if(ind[i] == 0)
                printf("%d ", v[i]);
        }
        printf("\n");
    }while(next_permutation(ind.begin(), ind.end()));
}
내림차순에서 오름차순으로
#include <bits/stdc++.h>
using namespace std;

int n, r;

int main (){
    cin >> n >> r;
    vector<int> v, ind;
    for(int i = 0; i < n ; i++)
        v.push_back(i);
    for(int i = 0; i < r; i++)
        ind.push_back(1);
    for(int i = 0; i < n - r; i++)
        ind.push_back(0);
    sort(ind.begin(), ind.end());

    do{
        for(int i = 0; i < n; i++){
            if(ind[i] == 1)
                printf("%d ", v[i]);
        }
        printf("\n");
    }while(next_permutation(ind.begin(), ind.end()));
}

입력 끝 판단하기

cin >> n >> m;
if(cin.eof()) return;

프로그래머스 42842 - 카펫

문제 설명

생각 및 접근

사족

  • Leo의 눈썰미에 박수를 보낸다.

본문

  • yellow를 토대로 노란색의 카펫을 먼저 만들어본 뒤, 노란색의 카펫을 기준으로 갈색 카펫을 덧붙인다. 덧붙인 결과, brown과 갈색 카펫의 수가 같다면 정답이므로, 갈색 카펫의 크기를 반환하면 된다.
  • 노란색의 카펫을 만들기 위한 과정
    • 약수를 토대로 하였다.
  • 갈색 카펫을 덧붙인 뒤, 그 갯수를 세는 과정
    brown == (yellowWidth + 2) * 2 + (yellowHeight + 2) * 2 - 4

코드

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

vector<int> solution(int brown, int yellow) {
    vector<int> answer;

    for(int i = 1; i <= yellow; i++){
        if(yellow % i == 0){
            int yellowWidth = max(i, yellow / i);
            int yellowHeight = min(i, yellow / i);

            if(brown ==  (yellowWidth + 2) * 2 + (yellowHeight + 2) * 2 - 4){
                answer.push_back(yellowWidth + 2);
                answer.push_back(yellowHeight + 2);
                break;
            }
        }
    }

    return answer;
}

채점 결과

프로그래머스 42841 - 숫자 야구

문제 링크

접근 및 생각

  • baseball을 보고 answer의 후보를 찾는 방법이 힘들어, 그냥 100부터 999까지 탐색해서 주어진 baseball에 알맞은 숫자를 찾는 방법으로 코드를 작성했다.

  • baseball에 적절한 숫자인지 판단해주는 함수 check

       // cmp는 비교할 숫자
      bool check(vector<vector<int>> baseball, int cmp){
          for(int i = 0; i < baseball.size(); i++){
              // temp는 baseball에서 주어진 숫자
              int S = 0, B = 0, temp = baseball[i][0];
    
              // 스트라이크 판별
              if((cmp / 100) == (temp / 100))             S++;
              if(((cmp / 10) % 10) == ((temp / 10) % 10)) S++;
              if((cmp % 10) == (temp % 10))               S++;
    
              // 볼 판별
              if((temp / 100) == ((cmp / 10) % 10) || (temp / 100) == (cmp % 10))         B++;
              if(((temp / 10) % 10) == (cmp / 100) || ((temp / 10) % 10) == (cmp % 10))   B++;
              if((temp % 10) == (cmp / 100) || (temp % 10) == ((cmp / 10) % 10))          B++;
    
              // baseball에 적절하지 않은 것이 하나라도 있으면, return false
              if(S != baseball[i][1] || B != baseball[i][2])  return false;
          }
          // baseball에 모두 적절하므로 return true
          return true;
      }
  • 100부터 999까지의 탐색 방식을 조금 특이하게 했다.

      int answer = 0;
    
      // i는 100의 자리, j는 10의 자리, k는 1의 자리
      for(int i = 1; i <= 9; i++){
          for(int j = 1; j <= 9; j++){
              for(int k = 1; k <= 9; k++){
                  // 야구게임 조건 상 각 자리의 숫자가 겹치면 안된다.
                  if(i == j || j == k || k == i)  continue;
    
                  int cmp = 100 * i + 10 * j + k;
                  if(check(baseball, cmp))  answer++;
              }
          }
      }
      return answer;

코드

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

bool check(vector<vector<int>> baseball, int cmp){
    for(int i = 0; i < baseball.size(); i++){
        int S = 0, B = 0, temp = baseball[i][0];

        if((cmp / 100) == (temp / 100))             S++;
        if(((cmp / 10) % 10) == ((temp / 10) % 10)) S++;
        if((cmp % 10) == (temp % 10))               S++;
        if((temp / 100) == ((cmp / 10) % 10) || (temp / 100) == (cmp % 10))         B++;
        if(((temp / 10) % 10) == (cmp / 100) || ((temp / 10) % 10) == (cmp % 10))   B++;
        if((temp % 10) == (cmp / 100) || (temp % 10) == ((cmp / 10) % 10))          B++;

        if(S != baseball[i][1] || B != baseball[i][2])  return false;
    }
    return true;
}

int solution(vector<vector<int>> baseball) {
    int answer = 0;
    for(int i = 1; i <= 9; i++){
        for(int j = 1; j <= 9; j++){
            for(int k = 1; k <= 9; k++){
                if(i == j || j == k || k == i)  continue;
                int cmp = 100 * i + 10 * j + k;
                if(check(baseball, cmp))  answer++;
            }
        }
    }
    return answer;
}

채점 결과

프로그래머스 42893 - 소수 찾기

문제 링크

생각 및 접근

  • 문제부터 소수 찾기. 그렇다면 소수를 체크하는 함수를 작성해야 했다.

      bool chkPrime(int a){
          if(a == 0 || a == 1)  return false;
          for(int i = 2; i <= sqrt(a); i++){
              if(a % i == 0)  return false;
          }
          return true;
      }
    • 함수를 더 최적화하기 위해서 i를 sqrt(a)까지 돌게 했다.

      • 왜? (출처 : Coding Monster님의 OpenTutorials )

          양의 정수 n, a, b에 대해 n = a * b (단, a <= b) 라고 해봅시다. 그러면 a와 b는 n의 약수가 됨을 알 수 있습니다. 
        
          a와 b의 값을 생각해봅시다. a의 최소값은 1이 되며, 이 때 b는 n이 됩니다.
          위의 식이 성립하기 위해서는 a가 점점 커질수록 b는 작아져야 하는 반비례 관계임을 알 수 있습니다. 
        
          위의 식 n=a*b에서 약수 a가 존재하면, 곱해서 n이 되는 짝 b가 항상 존재합니다.
          즉, 모든 약수는 곱해서 n이 되는 쌍이 존재하며, (a, b) 꼴 쌍에서 a <= b라고 할 경우 a의 최대값은 sqrt(n)가 됩니다. 
        
          그 이유는 a <= b 가 성립하는 상태에서 a가 가장 커질 수 있는 경우는 a == b인 경우이고, 이는 n = a * a 꼴이 됩니다.
  • string numbers의 숫자들을 하나씩 분리해서 다시 붙이는 작업을 해주어야 하는데, 이를 next_permutation으로 해결하였다. next_permutation를 통해서 나온 배열을 i = 1 .. numbers.size()까지 돌면서 substr 함수를 이용해 0번부터 i개의 string을 잘라낸다. 잘라낸 string을 소수 체크를 하고, 미리 선언해둔 map<int, int> m에 추가시킨다.

    • next_permutation란? 링크
      • 배열을 보고, 조합에 의한 순서대로 순회한다. 내림차순으로 정렬이 될 때까지 반복한다.
    • next_permutation를 사용할 때
      • 배열은 오름차순으로 정렬되어 있어야 한다.

코드

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

bool chkPrime(int a){
    if(a == 0 || a == 1)  return false;
    for(int i = 2; i <= sqrt(a); i++){
        if(a % i == 0)  return false;
    }
    return true;
}

int solution(string numbers) {
    int answer = 0, size = numbers.size();
    map<int, int> m;
    sort(numbers.begin(), numbers.end());

    do{
        for(int i = 1; i <= size; i++){
            string _temp = numbers.substr(0, i);
            int temp = stoi(_temp);
            if(m[temp] == 0 && chkPrime(temp)){
                m[temp]++;
            }    
        }
    }while(next_permutation(numbers.begin(), numbers.end()));

    for(auto k : m){
        if(k.second != 0)
            answer++;
    }
    return answer;
}

채점 결과

프로그래머스 42840 - 모의고사

문제 링크

생각 및 접근

  • 문제 갯수만큼 for문을 돌면서, 각 학생의 찍은 답이 정답이라면, 정답 갯수를 늘려주기로 했다.

      for(int i = 0; i < answers.size(); i++){
          if(answers[i] == (std1[i % 5]))   score[1]++;
          if(answers[i] == (std2[i % 8]))   score[2]++;
          if(answers[i] == (std3[i % 10]))  score[3]++;
      }
  • answers 순회를 마치고, 학생들 중에서 가장 높은 점수를 기록하고, 그 점수를 얻은 학생을 answerpush_back 한다.

      int max = *max_element(score + 1, score + 4);
      for(int i = 1; i <= 3; i++){
          if(max == score[i]) answer.push_back(i);
      }

코드

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

vector<int> answer;
int score[4];
int std1[5] = {1, 2, 3, 4, 5};
int std2[8] = {2, 1, 2, 3, 2, 4, 2, 5};
int std3[10] = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};

vector<int> solution(vector<int> answers) {
    for(int i = 0; i < answers.size(); i++){
        if(answers[i] == (std1[i % 5]))   score[1]++;
        if(answers[i] == (std2[i % 8]))   score[2]++;
        if(answers[i] == (std3[i % 10]))  score[3]++;
    }

    int max = *max_element(score + 1, score + 4);
    for(int i = 1; i <= 3; i++){
        if(max == score[i]) answer.push_back(i);
    }

    return answer;
}

채점 결과

+ Recent posts