백준 11723 c++

magicdrill·2025년 2월 14일
0

백준 문제풀이

목록 보기
551/655

백준 11723 c++

all과 empty의 경우 모든 수를 각각 초기화 할 때

for(int temp : S){
	temp = 1;
}

이런식으로 작성을 했는데, 이런 문법을 범위 기반 for문이라고 부르며, 또한 S 내부의 값이 변경되지 않았다. 왜냐하면 temp는 S의 값을 복사해왔을 뿐 참조하지는 않기 때문이다.
의도하던 대로 S값을 변경하려면

for(int &temp : S){
	temp = 1;
}

라고 작성해야 한다. 단 이 문제에서는 vector<bool> S를 사용했고, bool 벡터는 &문법이 적용되지 않는다.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void input_and_findAnswer() {
	int M, i, j, num;
	vector<bool> S(21, false);
	string state;

	cin >> M;
	for (i = 0; i < M; i++) {
		cin >> state;
		if (state == "add") {
			cin >> num;
			if (S[num] == false) {
				S[num] = true;
			}
		}
		else if (state == "remove") {
			cin >> num;
			if (S[num] == true) {
				S[num] = false;
			}
		}
		else if (state == "check") {
			cin >> num;
			if (S[num]) {
				cout << "1\n";
			}
			else {
				cout << "0\n";
			}
		}
		else if (state == "toggle") {
			cin >> num;
			S[num] = !S[num];
		}
		else if (state == "all") {
			for (j = 1; j <= 20; j++) {
				S[j] = true;
				//cout << S[j];
			}
			//cout << "\n";
		}
		else if (state == "empty") {
			for (j = 1; j <= 20; j++) {
				S[j] = false;
				//cout << S[j];
			}
			//cout << "\n";
		}
	}

	return;
}

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

	input_and_findAnswer();

	return 0;
}

0개의 댓글