Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 백준 17822
- 게리멘더링2
- 백준 2447
- 조세퍼스 순열
- 해시 구현
- 백준 1158
- 백준 5397
- dfs
- 백준 17471
- 별 찍기 10
- qorwns
- 버킷 정렬
- heap
- 원판 돌리기
- c#
- 백준 1406
- AVL 시간 복잡도
- 5397
- 구현
- 시간 복잡도
- Stack 이란
- 자료구조
- 백준
- 풀이
- 해시구현
- 백준 17779
- 1764
- ㅣ풀이
- C/C++ 구현
- 스택의 특징
Archives
- Today
- Total
홍시홍의 프로그래밍
[백준 16637] 괄호 추가하기 본문
분류
stack, 구현
요구사항
주어진 수식에서 괄호를 추가하여 만들 수 있는 수 중에서 가장 큰 수 찾기
풀이
문제 풀이 흐름은
1. dfs로 괄호 추가 위치 찾기
2. 괄호 추가 위치 다 찾았을 경우, stack을 이용해 수식 계산하기
- 괄호가 선택되어졌을때는 stack에서 제일 위에 있는거를 pop하고 연산한 뒤에 다시 넣는다
- 선택 안되었을 경우, 그냥 stack에 삽입한다.
다른 쉬운 풀이도 있는데 나는 어렵게 푼거 같다
문자열 변환 등등...
#include <iostream>
#include <queue>
#include <deque>
#include <string.h>
#include <string>
#include <algorithm>
using namespace std;
string str;
int visit[10];
int n;
int num[10];
string alph[10];
int ans = -987654321;
void dfs(int now) {
if (now >= n / 2 + 1) {
deque<string> dq;
dq.push_back(to_string(num[0]));
for (int i = 1; i <= (n / 2); i++) {
if (visit[i] == 0) {
dq.push_back(alph[i - 1]);
dq.push_back(to_string(num[i]));
// cout<<"push "<< alph[i-1] <<" "<<num[i]<<endl;
}
else if (visit[i] == 1) {
string now = dq.back();
// cout<<"pop"<<now<<endl;
dq.pop_back();
int nownum = stoi(now);
int nextnum = num[i];
int number = 0;
if (alph[i - 1] == "*") {
number = nownum*nextnum;
}
else if (alph[i - 1] == "+") {
number = nownum + nextnum;
}
else if (alph[i - 1] == "-") {
number = nownum - nextnum;
}
// cout<<"NUMber"<<number<<endl;
dq.push_back(to_string(number));
}
}
int tempans = stoi(dq.front());
dq.pop_front();
while (!dq.empty()) {
string now = dq.front();
//cout<<now<<endl;
dq.pop_front();
if (now == "*") {
tempans *= stoi(dq.front());
dq.pop_front();
}
else if (now == "+") {
tempans += stoi(dq.front());
dq.pop_front();
}
else if (now == "-") {
tempans -= stoi(dq.front());
dq.pop_front();
}
}
ans = max(ans, tempans);
return;
}
//골랐다.
visit[now] = 1;
dfs(now + 2);
//이번꺼 안골랏다
visit[now] = 0;
dfs(now + 1);
}
int main() {
scanf("%d", &n);
int numcnt = 0;
int alphacnt = 0;
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
scanf("%d", &num[numcnt++]);
}
if (i % 2 == 1) {
char ch;
scanf(" %c", &ch);
alph[alphacnt++] += ch;
}
}
dfs(1);
cout << ans << endl;
}
'알고리즘 문제풀이 > 백준' 카테고리의 다른 글
[백준 17135] 캐슬 디펜스 (0) | 2020.05.02 |
---|---|
[백준 17070] 파이프 옮기기1 (0) | 2020.05.02 |
[백준 1010] 다리 놓기 (0) | 2020.04.25 |
[백준 2163] 초콜릿 자르기 (0) | 2020.04.25 |
[백준 9461] 파도반 수열 (0) | 2020.04.25 |
Comments