Skip to content

[스택, 큐, 덱] 8월 27일 #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions BOJ_10757.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#include <iostream>
#include <string>
#include <vector>
using namespace std;

string addNumbers(string a, string b) {
vector<int> v_a, v_b, sum;
int carry = 0;

// 입력받은 a와 b 문자열을 벡터에 정수로 변환하여 저장한다.
for(int i = 0; i < a.length(); i++) {
v_a.push_back(a[i] - '0'); // '0'을 빼서 문자형 숫자를 정수형 숫자로 변환한다. (아스키코드 뺄셈)
}
for(int i = 0; i < b.length(); i++) {
v_b.push_back(b[i] - '0'); // '0'을 빼서 문자형 숫자를 정수형 숫자로 변환한다. (아스키코드 뺄셈)
}

// 최대 길이를 계산하고, 결과를 저장할 벡터의 크기 할당한다.
int maxLength = max(v_a.size(), v_b.size());
sum.resize(maxLength + 1, 0); // 최대 길이 + 1, 마지막 자리 캐리까지 고려!!

// 에러 난 이유: 뒤에서부터 거꾸로 연산 실행해야 한다!
int idx_a = v_a.size() - 1;
int idx_b = v_b.size() - 1;

// 에러 난 이유: 인덱스 접근 범위와 캐리값 코드 잘못 작성함
for (int i = maxLength; i >= 0; i--) {
int digitA = (idx_a >= 0) ? v_a[idx_a--] : 0;
int digitB = (idx_b >= 0) ? v_b[idx_b--] : 0;

int tempSum = digitA + digitB + carry; //tempSum은 i번째 자릿수에 저장되어야 하는 곳이다.
sum[i] = tempSum % 10; // 현재 자릿수의 결과,
carry = tempSum / 10; // 다음 자릿수로 넘길 캐리! (에러 조심)
}

// 벡터에서 앞자리의 0을 제거하고, 나머지 자릿수의 숫자를 문자열로 변환한다.
// 결과를 저장할 빈 문자열을 초기화한다. (에러 이유)
string result = "";

// 앞자리에 있는 0을 처리하기 위한 변수
bool leadingZero = true;

// 덧셈 결과 벡터의 각 자릿수를 문자열로 변환하여 결과에 추가한다.
for (int i = 0; i < sum.size(); i++) {
// 현재 자릿수의 값이 0이 아닌 경우, leadingZero 플래그를 false로 설정한다.
// 이는 이제 유효한 숫자가 나왔으므로 앞자리에 0이 더 이상 없음을 의미한다.
if (sum[i] != 0) {
leadingZero = false;
}

// leadingZero가 false일 때, 즉, 앞자리에 0이 없을 때만 결과 문자열에 현재 자릿수의 값을 추가한다.
if (!leadingZero) {
// 현재 자릿수의 값을 문자열로 변환하고, 결과 문자열에 추가한다.
result += to_string(sum[i]);
}
}

// 만약 결과 문자열이 비어있다면, 즉, 모든 자릿수가 0인 경우 "0"을 반환하고
// 빈 문자열인 경우는 모든 자릿수가 0일 때 발생할 수 있으므로 이를 처리한다.
return result.empty() ? "0" : result;

}

int main() {
string a, b;
cin >> a >> b;
cout << addNumbers(a, b) << '\n';
return 0;
}
51 changes: 51 additions & 0 deletions BOJ_1158.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include <iostream>
#include <list> // 원형 큐를 구현하기 쉬워서 list 함수를 사용

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2
c++에는 queue 자료구조가 구현되어 있습니다 ! 수업시간에 배운 queue를 사용하면 더 좋을 것 같습니다 ㅎㅎ

#include <vector> // 벡터는 순서대로 제거된 요소들을 저장하는 데 적합하고 벡터의 인덱스 접근은 O(1) 시간 복잡도로 빠르기 때문에 효율적이다.

using namespace std;

// 여러 개의 값을 반환할 수 있는 데이터 구조를 사용해야 하기 때문에 vector<int>로 선언해야 한다. int 타입으로 선언시, 다수의 값을 반환해야 하는 문제에서는 정보가 손실된다!!!
vector<int> getNumber(int N, int K) { // 요세푸스 순열을 계산하는 함수 (N = people, K = 제거되는 순서)

list<int> people; // 사람들을 저장할 리스트
vector<int> result; // 제거된 순서를 저장할 벡터

for (int i = 1; i <= N; ++i) { // 1부터 N까지 사람을 리스트에 추가한다.
people.push_back(i);
}

auto it = people.begin(); // 리스트의 시작 위치를 가리키는 이터레이터
// (auto는 it의 타입을 people.begin()이 반환하는 타입으로 자동으로 설정한다.)

while (!people.empty()) { // 모든 사람이 제거될 때까지 반복하는 while문
for (int i = 0; i < K - 1; ++i) { // K-1만큼 이터레이터를 이동한다. (K번째 사람을 찾기 위해)
++it; // 다음 사람으로 이동한다.
if (it == people.end()) it = people.begin(); // 리스트의 끝에 도달하면 다시 처음으로 돌아간다.
}

result.push_back(*it); // 현재 이터레이터가 가리키는 사람을 결과 벡터에 추가한다.

it = people.erase(it); // 현재 이터레이터가 가리키는 사람을 people 리스트에서 제거한다.
if (it == people.end()) it = people.begin(); // 리스트의 끝에 도달하면 처음으로 돌아간다.
}

return result; // 제거된 순서를 저장하고 있는 벡터를 반환한다.
}

int main() {
int N, K;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3

전역상수가 아닌 변수명은 대문자 사용을 지양하고 있습니다.

n, k 로 변경해주시면 좋을 것 같습니다 !

cin >> N >> K;

// 요세푸스 순열 계산
vector<int> number = getNumber(N, K);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

함수 따로 빼둔 거 너무 좋습니다 !!


// 제거된 순서를 저장하고 있는 벡터의 데이터를 출력한다.
cout << '<';
for (size_t i = 0; i < number.size(); ++i) {
cout << number[i];
if (i < number.size() - 1) cout << ", "; // 마지막 항목이 아닐 경우는 쉼표를 추가한다.
}
cout << '>' << '\n'; // (출력에 소요되는 시간을 최소화하기 위해 개행문자 '\n' 사용)

return 0;
}
52 changes: 52 additions & 0 deletions BOJ_4949.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <iostream>
#include <stack> // 스택 사용
#include <string> // 문자열 사용

using namespace std;

// 문자열 s가 괄호 균형을 이루는지 확인하는 함수
bool isBalanced(const string& s) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

함수화 너무 좋습니다🥰🥰🥰

stack<char> stk; // 괄호를 저장할 스택을 생성한다.


for (char ch : s) { // 문자열의 각 문자를 순회한다.
switch (ch) {
case '(': case '[': // 열린 (대)괄호일 때는 스택에 추가한다.
stk.push(ch);
break;
case ')':
// 닫힌 괄호일 때는
if (stk.empty() || stk.top() != '(') return false; // 스택이 비어있거나 올바른 짝이 아닐 경우 false(불균형)을 리턴한다.
stk.pop(); // 올바른 짝이면 스택에서 제거한다.
break;
case ']':
// 닫힌 대괄호일 때는
if (stk.empty() || stk.top() != '[') return false; // 스택이 비어있거나 올바른 짝이 아닐 경우 false(불균형)을 리턴한다.
stk.pop(); // 올바른 짝이면 스택에서 제거한다.
break;
default:
// 괄호가 아닌 다른 문자는 무시한다.
break;
}
}

// 모든 괄호가 닫히고 스택이 비어있다면 균형 잡힌 것이다.
return stk.empty();
Comment on lines +13 to +34
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

switch문으로 작성해주셨네요🤗 스택에 넣고 빼는 경우의 수 잘 분리해주셨습니다! 리턴 시점과 값도 좋아요👍👍

}

int main() {
string line; // 입력 문자열을 저장할 변수

//getline은 cin >> 처럼 공백이나 개행문자에서 입력을 끊지 않고 개행문자까지 포함한 전체의 줄을 읽기 때문에 훨씬 효율적이다.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사용하는 함수를 꼼꼼히 공부해주셨네요🥰 훌륭합니다👍👍👍

while (getline(cin, line)) { // 입력을 한 줄씩 읽는다.
if (line == ".") break; // 입력이 "."이면 종료한다.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. 중괄호가 없으면 코드를 수정할 일이 생길 때 불편할 수 있어요. 특히, 협업할 때는 나중에 추가한 중괄호로 인해 git에서 충돌이 날 수 있답니다...!! 😱 코드가 한 줄이더라도 중괄호 넣으시는 걸 권장드립니다👍


// 입력 문자열의 괄호 균형을 확인
if (isBalanced(line)) {
cout << "yes" << '\n'; // 균형 잡힌 경우 "yes" 출력
} else {
cout << "no" << '\n'; // 균형 잡히지 않은 경우 "no" 출력
}
}
return 0; // 프로그램 종료
}