반응형
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
- function_template
- class_template
- sstream
- 예제
- sort
- '0'
- STL
- singly Linked List
- list
- 백준
- qsort
- deletion
- 구현
- Algorithm
- Heap
- connected_component
- data_structure
- 총정리
- Pair
- 문법
- Articulation_Point
- Critical_Path_Analysis
- 알고리즘
- 자료구조
- c++
- 5397
- Biconnected_Component
- red-black tree
- template
- 13305
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) 총정리 및 예제
백준 1541번 문제
https://www.acmicpc.net/problem/1541
반응형
'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