맞힌 코드
#include <bits/stdc++.h>
using namespace std;
int m;
int arr[21] = {0,};
int main(void){
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> m;
for (int i=0; i<m; i++){
string str;
cin >> str;
if (str=="all"){
/*
for (int i=1; i<21; i++){
arr[i] = 1;
}
*/
fill(arr+1, arr+21, 1);
}
else if (str=="empty"){
/*
for (int i=1; i<21; i++){
arr[i] = 0;
}
*/
fill(arr+1, arr+21, 0);
}
else{
int x;
cin >> x;
if (str=="add"){
arr[x] = 1;
}
else if (str=="remove"){
arr[x] = 0;
}
else if (str=="check"){
if (arr[x]==1)
cout << 1 << '\n';
else
cout << 0 << '\n';
}
else if (str=="toggle"){
if (arr[x]==1){
arr[x] = 0;
}
else{
arr[x] = 1;
}
}
}
}
}
ios_base::sync_with_stdio(0); cin.tie(0); 이 코드 추가했더니 시간초과 없어졌음.
특정 값으로 배열 초기화할 때 for문 돌리려 했는데 fill(arr+1, arr+21, 0); 이런식으로도 초기화 가능
틀린 코드
시간 초과 떴음
#include <bits/stdc++.h>
using namespace std;
int m;
vector<int> v;
int main(void){
cin >> m;
for (int i=0; i<m; i++){
string str;
cin >> str;
if (str=="all" || str=="empty"){
v = {};
if (str=="all"){
//for (int i=1; i<=20; i++){
// v.push_back(i);
//}
}
}
else{
int x;
cin >> x;
bool a;
int size = v.size();
for (int i=0; i<size; i++){
if (v[i]==x){
a = true;
}
else{
a = false;
}
}
if (str=="add" || str=="toggle"){
if (a)
continue;
else
v.push_back(x);
}
else if (str=="remove" || str=="toggle"){
if (a){
v.erase(remove(v.begin(), v.end(), 5), v.end());
}
}
else if (str=="check"){
if (a)
cout << 1;
else
cout << 0;
}
}
}
}
벡터를 쓰는 게 아니었나...
각 인덱스가 수라고 생각하고 개수를 원소로 하는 배열로 풀어보겠음.
코드 작성 방식 바꾼 후에 안 지운 코드 없는지 확인
'Algorithm' 카테고리의 다른 글
[백준/BOJ] 20125번 쿠키의 신체 측정 C++ (0) | 2024.11.07 |
---|---|
[백준/BOJ] 9655번 돌 게임 C++ (0) | 2024.11.07 |
[소프티어/Softeer] 나무 공격 C++ (0) | 2024.11.01 |
[백준/BOJ] 2292번 벌집 C++ (0) | 2024.10.15 |
[백준/BOJ] 23971번 ZOAC 4 (0) | 2024.10.15 |