C++)
1. vector
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
vector<int> v;
int n, k;
cin >> n >> k;
for (int i = 1; i <= n; i++)
v.push_back(i);
string ans = "";
int cur = 0;
while (!v.empty()) {
if (v.size() == 1) {
ans += to_string(v.front());
break;
}
cur = (cur + (k - 1)) % v.size(); // 자기 자신을 이미 포함하므로 -1 하기
ans += (to_string(v.at(cur)) + ", ");
v.erase(v.begin() + cur);
}
cout << "<" << ans << ">";
return 0;
}
2. list
#include <iostream>
#include <list>
#include <string>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
list<int> l;
int n, k;
cin >> n >> k;
for (int i = 1; i <= n; i++)
l.push_back(i);
string ans = "";
int cnt = 1;
list<int>::iterator it = l.begin();
while (!l.empty()) {
if (cnt == k) {
ans += (to_string(*it) + ", ");
it = l.erase(it);
}
else
it++;
cnt = (cnt == k) ? 1 : cnt+1;
if (it == l.end())
it = l.begin();
}
cout << "<" << ans.substr(0, ans.length()-2) << ">";
return 0;
}
Python)
import sys
read = sys.stdin.readline
n, k = map(int, read().rstrip().split())
arr = [i+1 for i in range(n)]
ans = []
cur = 0
while arr:
cur = (cur + (k-1)) % len(arr) # 자기 자신도 포함되어 있으므로 -1 해주기
ans.append(str(arr[cur]))
arr.pop(cur)
print("<" + ', '.join(ans) + ">")'백준 1 > 자료구조' 카테고리의 다른 글
| [백준 4949] 균형잡힌 세상 (C++/Python) (0) | 2020.12.06 |
|---|---|
| [백준 10866] 덱 (C++/Python) (0) | 2020.12.06 |
| [백준 2161] 카드1 (C++/Python) (0) | 2020.12.06 |
| [백준 10845] 큐 (C++/Python) (0) | 2020.12.06 |
| [백준 9012] 괄호 (C++/Python) (0) | 2020.12.06 |