본문 바로가기

C++

바킹독의 실전 알고리즘 [연결 리스트]

#1406 에디터

#include <bits/stdc++.h>
using namespace std;

int main(void) {
	ios::sync_with_stdio;
	cin.tie(0);
	string s1;
	int n;
	cin >> s1;
	list<char> L;
	for (auto c : s1) L.push_back(c);
	auto cursor = L.end();
	cin >> n;
	for (int i = 0; i < n; i++) {
		char s2;
		cin >> s2;
		if (s2 == 'L') {
			if (cursor != L.begin()) cursor--;
		}
		else if (s2 == 'D') {
			if (cursor != L.end()) cursor++;
		}
		else if (s2 == 'B') {
			if (cursor != L.begin()) {
				cursor--;
				cursor = L.erase(cursor);
			}
		}
		else if (s2 == 'P') {
			char add;
			cin >> add;
			L.insert(cursor, add);
		}
	}
	for (auto c : L) cout << c;
}

#5307 키로거

#include <bits/stdc++.h>
using namespace std;

int main(void) {
	ios::sync_with_stdio;
	cin.tie(0);
	int n;
	cin >> n;
	while (n--) {
		string s2;
		cin >> s2;
		list<char> L;

		auto cursor = L.begin();
		for (auto c : s2) { 
			if (c == '<') {
				if (cursor != L.begin()) cursor--;
			}
			else if (c == '>') {
				if (cursor != L.end()) cursor++;
			}
			else if(c == '-') {
				if (cursor != L.begin()) {
					cursor--;
					cursor = L.erase(cursor);
				}
			}
			else {
				L.insert(cursor, c);
			}
		}
		for (auto c : L) cout << c;
		cout << '\n';
	}
	
}

#1158 요세푸스 문제

#include <bits/stdc++.h>
using namespace std;

int main(void) {
	ios::sync_with_stdio;
	cin.tie(0);
	
	int n, k;
	cin >> n >> k;
	vector <int> v1, v2;
	for (int i = 1; i <= n; i++) v1.push_back(i);
	for (int i = 0; v2.size() < n; i++) {
		if (i % k == k - 1) v2.push_back(v1[i]);
		else v1.push_back(v1[i]);
	}
	cout << "<";
	for (int i = 0; i < n; i++) {
		if (i == n - 1) cout << v2[i];
		else cout << v2[i] << ", ";
	}
	cout << ">";
}

- vector를 많이 사용해본적이 없어 좀 어려웠던것 같다.