Skip to content
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

0923 백트래킹 #8

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
68 changes: 68 additions & 0 deletions 09월 20일 - 구현 & 코너케이스/2840.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<char> wheel; // 바퀴 칸별 문자 저장
int idx_arrow = 0; // 현재 화살표가 가리키는 칸의 인덱스
bool valid = true; // 종이에 해당하는 행운의 바퀴 있는지 여부


void updateState(int& idx_arrow, int change, char alphabet, int n) {
idx_arrow = (idx_arrow + change) % n;

// 지금 알파벳이 들어갈 자리에 이미 다른 알파벳이 있는 경우
if (wheel[idx_arrow] != '?' && wheel[idx_arrow] != alphabet) {
valid = false;
return;
}

else wheel[idx_arrow] = alphabet;
}

int main() {

int n, k; // 바퀴 칸 수 n, 회전 횟수 k
cin >> n >> k;

wheel.assign(n, '?');


int change;
char alphabet;

while (k-- && valid) {
cin >> change >> alphabet;
updateState(idx_arrow, change, alphabet, n);
}

// 원래는 돌리면 반시계방향에서 숫자가 넘어온다. 따라서 reverse로 순서 재정렬
reverse(wheel.begin(), wheel.end());
idx_arrow = n-1 - idx_arrow;


// 같은 알파벳이 중복으로 들어가있는지 확인
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (wheel[i] != '?' && wheel[i] == wheel[j]) {
valid = false;
}
}
}


// [case 1] 종이에 해당하는 행운의 바퀴 없는 경우
if (!valid) {
cout << "!" << "\n";
return 0;
}

// [case 2] 종이에 해당하는 행운의 바퀴 있는 경우
int idx;
for (int i = 0; i < n; i++) {
cout << wheel[(i + idx_arrow) % n];
}

return 0;
}
53 changes: 53 additions & 0 deletions 09월 20일 - 구현 & 코너케이스/3226.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int getCharge(string& start, string& time) {
int charge = 0;

// 자정 00:00으로부터 흐른 minute으로 통화 시작, 종료 시각 표현하기
int call_start = stoi(start.substr(0, 2)) * 60 + stoi(start.substr(3, 2));
int call_fin = call_start + stoi(time);


if (call_start >= 7 *60 && call_fin < 19 * 60) {
charge += (stoi(time) * 10);
}

// 자정 넘어서 통화 시작하는 경우 추가해야 함
if (call_start >= 19 * 60 && call_fin < 26 * 60 || call_start >= 0 && call_fin < 7 * 60) {
charge += (stoi(time) * 5);
}

if (call_start < 7 * 60 && call_fin >= 7*60) {
charge += (7 * 60 - call_start) * 5;
charge += (call_fin - 7*60) * 10;
}

if (call_start < 19 * 60 && call_fin >= 19 * 60) {
charge += (19*60 - call_start) * 10;
charge += (call_fin - 19*60) * 5;
}

return charge;
}

int main() {

int n; // 전화의 수, 전화 요금
cin >> n;

int answer = 0;

string start, time;
while (n--) {
cin >> start >> time;
answer += getCharge(start, time);
}

cout << answer << "\n";

return 0;
}
66 changes: 66 additions & 0 deletions 09월 20일 - 구현 & 코너케이스/5397.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#include <iostream>
#include <stack>

using namespace std;

string printPW(string input) {
// [ left stack <-] [커서] [-> right stack ]
stack<char> left; // 커서 기준 왼쪽 문자들
stack<char> right; // 커서 기준 오른쪽 문자들
char temp;

for (int i = 0; i < input.size(); i++) {
if (input[i] == '<' && !left.empty()) {
temp = left.top();
right.push(temp);
left.pop();
}

else if (input[i] == '>' && !right.empty()) {
temp = right.top();
left.push(temp);
right.pop();
}

else if (input[i] == '-' && !left.empty()) {
left.pop();
}

else if (input[i] >= 'A' && input[i] <= 'z' // 알파벳인 경우
|| input[i] >= '0' && input[i] <= '9') { // 숫자인 경우
left.push(input[i]);
}
}

// 최종 비밀번호 출력
string answer = "";
while (!left.empty()) {
right.push(left.top());
left.pop();
}

while (!right.empty()) {
answer += right.top();
right.pop();
}

return answer;
}

int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);

int n; // 테스트 케이스 개수
cin >> n;

string input;

while (n--) {
cin >> input;
cout << printPW(input) << "\n";
}

return 0;
}
60 changes: 60 additions & 0 deletions 09월 23일 - 백트래킹/10971.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
const int SIZE = 10;

int cost[SIZE][SIZE]; // 비용 행렬
bool check[SIZE] = { false }; // 경로에 이미 사용된 도시인지 체크
int n; // 도시 개수
int minCost = 2147483647; // 최소비용, int 최대값으로 초기화


// start: 시작 도시 인덱스, current: 최근 방문 도시 인덱스, cost_current: 쌓인 비용, count : 지금까지 경로에 사용된 도시 개수
void backTracking(int start, int current, int cost_current, int count) {

// case 1) n개 도시로 여행 경로 완성한 경우
if (count == n) {

// 출발지로 돌아오는 길 있는 경우
if (cost[current][start] > 0) minCost = min(minCost, cost_current + cost[current][start]);

return;
}

// case 2) 경로 탐색
for (int i = 0; i < n; i++) {

// 방문조건 : (1) 방문한 적 X, (2) 직전 도시와 이어져 있음
if (!check[i] && cost[current][i] > 0) {
check[i] = true;
backTracking(start, i , cost_current + cost[current][i], count + 1);

check[i] = false;
}
}
}


int main() {

cin >> n; // 도시의 수

for (int i = 0; i < n; i++ ) {
for (int j = 0; j < n; j++) {
cin >> cost[i][j];
}
}


for (int i = 0; i < n; i++) {
check[i] = true;
backTracking(i, 0, 0, 1); // 출발지 도시는 방문하며 시작하므로 count = 1부터 시작
check[i] = false;
}

cout << minCost << "\n";

return 0;
}
51 changes: 51 additions & 0 deletions 09월 23일 - 백트래킹/15663.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
const int SIZE = 8;

int n, m;
vector<int> num; // 입력받은 숫자 목록 (중복 가능)
vector<bool> check(SIZE); // 수열에 사용한 적 있 숫자인지 여부
vector<int> result(SIZE); // 수열 만드는 벡터


void backTracking(int len) { // len : 지금까지 만든 수열의 길이
if (len == m) {
for(int i= 0; i< m; i++) {
cout << result[i] << " ";
}
cout << "\n";
return;
}

// 수열 만들기
int before = -1; // 바로 이전에 선택한 값 저장
for (int i = 0; i < num.size(); i++) {
if (!check[i] && num[i] != before) {
result[len] = num[i];
check[i] = true;
before = num[i]; // before 갱신
backTracking(len + 1);

check[i] = false;
}
}
Comment on lines +23 to +34

Choose a reason for hiding this comment

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

맞아요! 이전 수열의 마지막 항과 새로 추가할 값이 같으면 중복된 수열이 된다는 점을 활용하면 되는 문제였어요.
기본 재귀 순열에서 이전에 선택된 값을 저장하는 before 변수를 사용하여
cnt 번째 같은 숫자가 중복되서 사용되지 않도록 구현해주셨네요!🥰

}

int main() {

cin >> n >> m; // m : 수열 길이

int input;
for (int i = 0; i < n; i++) {
cin >> input;
num.push_back(input);
}

sort(num.begin(), num.end()); // 사전순으로 증가하는 수열 만들기 위해 크기 순 정렬
backTracking(0);

return 0;
}