[프로그래머스][Level2] 수식 최대화 c++

2022. 10. 21. 13:10·🍞 Algorithm/Programmers
https://programmers.co.kr/learn/courses/30/lessons/67257 

 

풀이 과정

연산이 string 자료형으로 주어졌기 때문에, 반복문을 돌려  
num 벡터에 숫자를 담고, op 벡터에 연산자를 담는다.

그리고 3가지 연산문자를 준비해 순열 알고리즘을 쓴다.  
그 이유는 우선순위를 정하기 위해서다.

처음에는 *, +, - 순으로 우선순위가 정해져 계산을 하는데,  
계산을 하는 도중에 원래 벡터들을 삭제하는 과정이 있기 때문에  
num벡터와 op벡터를 순열이 시작될 때마다 temp 벡터로 만들어줘야한다.

- 새로 알게된 점!
  max를 쓰려면 두 자료형이 맞아야 한다.  
  예를 들어 max(int, long long)이면 안 되고, max(long long, long long)이여야만 한다!

 

#include <string>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

long long calc(long long a, long long b, char c){
    if(c == '+') return a + b;
    else if(c == '-') return a - b;
    else if(c == '*') return a * b;
}

long long solution(string expression) {
    long long answer = 0;
    vector<long long> num; // 숫자
    vector<char> op; // 연산자

    string temp = "";
    for(int i = 0; i < expression.size(); i++){
        if('0' <= expression[i] && expression[i] <= '9'){
            temp += expression[i];
        }
        else{
            num.push_back(stoll(temp));
            op.push_back(expression[i]);
            temp = "";
        }
    }
    if(temp != "") num.push_back(stoll(temp));

    char oplist[3] = {'+', '-', '*'};
    sort(oplist, oplist + 3);

    do{
        vector<long long> num_temp = num;
        vector<char> op_temp = op;
        for(int i = 0; i < 3; i++){ // oplist
            for(int j = 0; j < op_temp.size(); j++){ // 실제 연산자
                if(oplist[i] == op_temp[j]){
                    num_temp[j] = calc(num_temp[j], num_temp[j + 1], op_temp[j]);
                    num_temp.erase(num_temp.begin() + j + 1);
                    op_temp.erase(op_temp.begin() + j);
                    j--;
                }
            }
        }
        answer = max(answer, abs(num_temp[0]));
    }while(next_permutation(oplist, oplist + 3));

    return answer;
}
저작자표시 (새창열림)

'🍞 Algorithm > Programmers' 카테고리의 다른 글

[프로그래머스][Level2] 오픈채팅방 c++  (0) 2022.10.21
[프로그래머스][Level2] 영어 끝말잇기 c++  (0) 2022.10.21
[프로그래머스][Level2] 배달 c++  (0) 2022.10.21
[프로그래머스][Level2] [3차] n진수 게임 c++  (0) 2022.10.21
[프로그래머스][Level2] 카펫 c++  (0) 2022.10.21
'🍞 Algorithm/Programmers' 카테고리의 다른 글
  • [프로그래머스][Level2] 오픈채팅방 c++
  • [프로그래머스][Level2] 영어 끝말잇기 c++
  • [프로그래머스][Level2] 배달 c++
  • [프로그래머스][Level2] [3차] n진수 게임 c++
박빵이
박빵이
2025년에도 갓생살기
  • 박빵이
    기억보다 기록
    박빵이
  • 전체
    오늘
    어제
    • 분류 전체보기 (337)
      • 🍞 FrontEnd (97)
        • HTML+CSS (4)
        • JavaScript (17)
        • TypeScript (4)
        • React (52)
        • Next.js (2)
        • Android (15)
      • 🍞 BackEnd (24)
        • Java (15)
        • Node.js (6)
        • Spring (1)
      • 🍞 Cloud & Infra (0)
        • AWS SAA (0)
        • Microsoft Azure (0)
      • 🍞 Algorithm (147)
        • C++ (4)
        • Baekjoon (41)
        • Programmers (97)
      • 🍞 Computer Science (18)
        • 운영체제 (1)
        • 데이터 통신 (6)
        • 네트워크 (6)
        • 데이터베이스 (1)
      • 🍞 대외활동 & 부트캠프 (42)
        • 삼성 청년 SW 아카데미 (1)
        • LG유플러스 유레카 (0)
        • 한국대학생IT경영학회 (1)
        • IT연합동아리 UMC (17)
        • 길벗 블로깅 멘토 (18)
        • IT연합동아리 피로그래밍 (3)
        • 개발 컨퍼런스 (2)
  • 블로그 메뉴

    • Admin
  • 링크

    • GitHub
  • 인기 글

  • 태그

    Front
    level1
    map
    level2
    프로그래머스
    코딩자율학습
    길벗 블로깅 멘토링
    백준
    Android
    위상정렬
    umc
    JavaScript
    유니온파인드
    react
    길벗 블로깅 멘토
    C++
    코틀린
    Java
    알고리즘
    안드로이드
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
박빵이
[프로그래머스][Level2] 수식 최대화 c++
상단으로

티스토리툴바