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 |
Tags
- 그래프
- 정석학술정보관
- DP
- Stack
- 자료구조
- 정석
- Operating System
- 백준
- 구현
- 컴퓨터공학과
- 코테
- 코딩
- 북리뷰
- 개발
- vector
- 컴공
- bfs
- 알고리즘
- 오에스
- 스택
- 문제풀이
- 브루트포스
- OS
- c++
- 너비우선탐색
- cs
- 오퍼레이팅시스템
- coding
- 컴공과
- Computer science
Archives
- Today
- Total
Little Jay
[C++] 백준 1744번 - 수 묶기 본문
너무 어렵게 접근했던 문제이다.
뇌가 처음에는 너무 꼬여서 양수만 있을때, 음수있을때, 음수랑 0만 있을때, 0과 양수만 있을때
하나의 vector 컨테이너에서 조건문을 10개 이상 만들면서 처리를 하려고 했다.
너무 복잡해지자 이걸 어떻게 효율적으로 처리할까 고민하다가
양수와 음수를 따로 받는 방법을 생각하게 되었다.
1은 수를 묶을때 의미가 없다. 예를 들어
1 + 3 은 1 * 3 보다 무조건 크기 때문에 1이 들어올때는 바로 결과물을 담는 컨테이너에 담아주면 된다.
양수와 음수는 서로 묶어주지만 각 벡터의 개수가 홀수인지, 양수인지 구분해주면 된다.
#include <iostream>
#include <vector>
#include <algorithm>
#define endl '\n'
using namespace std;
int n, cumsum;
vector<int> pos;
vector<int> neg;
vector<int> zeros;
vector<int> ans;
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n;
while (n--) {
int num; cin >> num;
if (num < 0) neg.push_back(num);
else if (num == 0) zeros.push_back(num);
else {
if (num == 1) ans.push_back(num);
else pos.push_back(num);
}
}
sort(pos.begin(), pos.end());
sort(neg.begin(), neg.end());
if (pos.size() % 2 != 0) {
ans.push_back(pos[0]);
}
for (int i = pos.size() - 1; i > 0; i -= 2) {
ans.push_back(pos[i] * pos[i - 1]);
}
if (neg.size() % 2 != 0) {
if (zeros.size()) {
zeros.pop_back();
}
else {
ans.push_back(neg[neg.size() - 1]);
}
}
for (int i = 0; i < static_cast<int>(neg.size() - 1); i += 2) {
ans.push_back(neg[i] * neg[i + 1]);
}
for (int i = 0; i < ans.size(); i++) {
cumsum += ans[i];
}
cout << cumsum << endl;
return 0;
}
'알고리즘 > BOJ' 카테고리의 다른 글
[C++] 백준 1076번 - 저항 (0) | 2022.02.18 |
---|---|
[C++] 백준 6588번 - 골드바흐 추측 (0) | 2022.02.11 |
[C++] 백준 15312번 - 이름 궁합 (0) | 2022.02.06 |
[C++] 백준 13303번 - 타일 장식물 (0) | 2022.02.06 |
[C++] 백준 7662번 - 이중 우선순위 큐(multiset) (0) | 2022.01.13 |
Comments