Skip to content

Commit bdb321f

Browse files
committed
C++ Ch.01 Sample Code (Programmers)
1 parent 1edee52 commit bdb321f

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 문제: 주식가격 (https://programmers.co.kr/learn/courses/30/lessons/42584)
3+
* Difficulty: Level 2
4+
* Comment: 스택을 활용한 문제입니다.
5+
* 새로 들어오는 값이 스택의 top 보다 작으면 스택의 값을 빼버리고, 얼마나 오래 있었는지 리턴하면 됩니다.
6+
* 따라서 들어오는 시간을 기록하기 위해 stack의 구조를 pair로 해주셔야 합니다.
7+
*/
8+
9+
#include <string>
10+
#include <vector>
11+
#include <stack>
12+
#include <iostream>
13+
using namespace std;
14+
15+
vector<int> solution(vector<int> prices) {
16+
vector<int> answer(prices.size(), 0);
17+
stack<pair<int, int>> st;
18+
19+
for(int i = 0; i < prices.size(); i++) {
20+
int price = prices[i];
21+
while(!st.empty() && st.top().second > price) {
22+
pair<int, int> p = st.top(); st.pop();
23+
answer[p.first] = i - p.first;
24+
}
25+
st.push({i, price});
26+
}
27+
28+
while(!st.empty()) {
29+
pair<int, int> p = st.top(); st.pop();
30+
answer[p.first] = prices.size() - p.first - 1;
31+
}
32+
33+
return answer;
34+
}
35+
36+
int main() { // Driver
37+
vector<int> vec = {1, 2, 3, 2, 3};
38+
vector<int> result = solution(vec);
39+
40+
for(int i : result) cout << i << ' ';
41+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 문제: 기능개발 (https://programmers.co.kr/learn/courses/30/lessons/42586)
3+
* Difficulty: Level 2
4+
* Comment: "뒤에 있는 기능은 앞에 있는 기능이 배포될 때 함께 배포된다." 라는 말에 주목하세요.
5+
* 즉, 모든 기능이 순차적으로 배포되어야 합니다.
6+
* 순차적이면 어떤 자료구조를 사용하면 될까요? 큐죠?
7+
*/
8+
9+
#include <string>
10+
#include <vector>
11+
#include <queue>
12+
#include <iostream>
13+
using namespace std;
14+
15+
vector<int> solution(vector<int> progresses, vector<int> speeds) {
16+
vector<int> answer;
17+
queue<pair<int, int>> q;
18+
int time = 0;
19+
20+
for(int i = 0; i < progresses.size(); i++) q.push({progresses[i], i});
21+
while(!q.empty()) {
22+
int X = q.front().first, Y = speeds[q.front().second];
23+
int cnt = 1;
24+
25+
while(X + Y * time < 100) time++;
26+
q.pop();
27+
28+
while(!q.empty()) {
29+
if(q.front().first + speeds[q.front().second] * time >= 100) {
30+
q.pop();
31+
cnt++;
32+
} else break;
33+
}
34+
35+
answer.push_back(cnt);
36+
}
37+
return answer;
38+
}
39+
40+
int main() { // Driver
41+
vector<int> progress = {95, 90, 99, 99, 80, 99};
42+
vector<int> speeds = {1, 1, 1, 1, 1, 1};
43+
vector<int> result = solution(progress, speeds);
44+
45+
for(int i : result) cout << i << ' ';
46+
}

0 commit comments

Comments
 (0)