반응형
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 | 29 | 30 | 31 |
Tags
- Articulation_Point
- singly Linked List
- 13305
- qsort
- red-black tree
- sort
- deletion
- Pair
- 문법
- template
- list
- 5397
- 총정리
- connected_component
- 자료구조
- sstream
- Algorithm
- STL
- function_template
- 구현
- '0'
- Critical_Path_Analysis
- c++
- data_structure
- 알고리즘
- Heap
- 백준
- class_template
- Biconnected_Component
- 예제
Archives
- Today
- Total
- Today
- Total
- 방명록
어제의 나보다 성장한 오늘의 나
[c++][Greedy] 백준 1541번 문제 풀이 본문
반응형
풀이 :
① 입력 된 문장을 +,- 와 숫자로 나눈다. ( substr 사용)
② 조건에 맞게 계산을 한다.
가장 작은 값이 결과로 나오도록 해야 하므로 - 가 나오기 전까지는 모든 숫자를 더 해주고,
-가 한 번이라도 나오면 그 이후로는 모두 빼주면 된다.
Coding
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int args ,char** argv){
string str;
cin >> str;
vector<char> ops; // str에 들어있는 + , - 순서대로 저장.
vector<int> nums; // str에 들어있는 숫자들 순서대로 저장.
int first_index = 0;
int last_index = 0;
// 입력된 문장을 + , - 와 숫자들로 분류. substr 사용.
for(int i = 0 ; i < str.size() ; ++i){
if(str[i] == '+'){
nums.push_back(stoi(str.substr(first_index , last_index - first_index)));
ops.push_back(str[i]);
first_index = i + 1;
last_index++;
}
else if(str[i] == '-'){
nums.push_back(stoi( str.substr(first_index , last_index - first_index)));
ops.push_back(str[i]);
first_index = i + 1;
last_index++;
}
else if(i==str.size() - 1){
nums.push_back(stoi(str.substr(first_index , last_index + 1 - first_index)));
}
else{
last_index++;
}
}
int total = nums[0];
for(int i = 0 ; i < ops.size() ; ++i){
if(ops[i]=='-'){
for(int j = i + 1 ; j < nums.size() ; ++j){
total -= nums[j];
}
break;
}
else if(ops[i]=='+'){
total += nums[i+1];
}
}
cout << total;
}
substr에 대하여 자세히 알고 싶다면 아래 글을 참조 하자.
2022.02.19 - [c++/문법] - [c++] 문자열 자르기 / 쪼개기 (Substr , Sstream , Strtok) 총정리 및 예제
[c++] 문자열 자르기 / 쪼개기 (Substr , Sstream , Strtok) 총정리 및 예제
1) s.substr(시작 위치 , 문자열의 길이) string s = "0123456789"; string subs1 = s.substr(2,5); // subs1 = "23456" string s = "0123456789"; string subs1 = s.substr(5); // subs1 = "56789" string s = "0..
8156217.tistory.com
백준 1541번 문제
https://www.acmicpc.net/problem/1541
1541번: 잃어버린 괄호
첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다
www.acmicpc.net
반응형
'c++ > 백준 문제 풀이' 카테고리의 다른 글
[c++][Greedy] 백준 10610번 문제 풀이 (0) | 2022.02.22 |
---|---|
[c++][Greedy] 백준 1789번 문제 풀이 (0) | 2022.02.22 |
[c++][Greedy] 백준 11399번 문제 풀이 (0) | 2022.02.20 |
[c++][Greedy] 백준 13305번 문제 풀이 (0) | 2022.02.19 |
[c++][문제 풀이] 백준 18870번 <좌표 압축> (0) | 2022.02.13 |
Comments