본문 바로가기
Programming/Baekjoon Online Judge

[BOJ 백준 C언어] 31881번 : K512에 바이러스 퍼뜨리기

by 장경혁tv 2025. 8. 1.

목차

1. 문제

2. 풀이

3. 메시지

1. 문제

https://www.acmicpc.net/problem/31881

2. 풀이

언어 : C

구현에는 다양한 방법이 있지만 배열로 구현했다.

첫 번째 줄에 N (1  N ≤ 2 * 10⁵) 과 Q (1  Q ≤ 2 * 10⁵) 에 대한 입력을 받고 Q+1번째 줄까지 다음 쿼리를 처리한다.

쿼리

: 승형이가 번 컴퓨터를 감염시킨다.

단, 승형이는 이미 감염된 컴퓨터를 다시 감염시킬 수 있다.
이때는 아무 일도 벌어지지 않는다. (1 ≤ x ≤ n)
: 근수가 번 컴퓨터를 치료하여 감염되지 않은 상태로 만든다.
단, 근수는 감염되지 않은 멀쩡한 컴퓨터를 치료할 수 있다.

이때는 아무 일도 벌어지지 않는다. (1 ≤ x ≤ n)
 ●  현재 K512의 감염되지 않은 컴퓨터의 개수를 출력한다.

 

프로그래밍

viralComputers[200000] = { 0, }; 으로 배열의 모든 원소를 0(감염되지 않음)으로 초기화한다. (1이면 감염됨)

그리고 따로 numberViralComputer = 0; 으로 선언한 변수가 있는데, 이는 감염된 컴퓨터의 개수를 의미한다.

쿼리 1에 대한 입력으로 x가 주어지는데 viralComputers[x - 1] = 1; (감염된 상태로)

만약 viralComputers[x - 1] == 0이면 감염되지 않은 컴퓨터를 감염시킨 것이므로 numberViralComputer++;

쿼리 2에 대한 입력으로 x가 주어지는데 viralComputers[x - 1] = 0; (감염되지 않은 상태로)

만약 viralComputers[x - 1] == 1이면 감염된 컴퓨터를 치료한 것이므로 numberViralComputer--;

쿼리 3에 대한 출력은 (감염되지 않은 컴퓨터의 개수) = (전체 컴퓨터의 개수) - (감염된 컴퓨터의 개수)이기 때문이다.

 

참고로 쿼리는 case 1, case 2, case 3로 switch를 사용하여 구현했다.

소스코드

https://github.com/NewLandTV/Baekjoon-Online-Judge/blob/main/C/31881.c

 

Baekjoon-Online-Judge/C/31881.c at main · NewLandTV/Baekjoon-Online-Judge

This repository is where problems solved on the Baekjoon Online Judge site are uploaded. - NewLandTV/Baekjoon-Online-Judge

github.com

#include <stdio.h>

int main(void)
{
	int n, q;
	int query, x;
	int viralComputers[200000] = { 0, };
	int numberViralComputer = 0;
	
	scanf("%d %d", &n, &q);
	
	while (q--)
	{
		scanf("%d", &query);
		
		switch (query)
		{
			case 1:
				scanf("%d", &x);
				
				x--;
				
				if (viralComputers[x] == 0)
				{
					numberViralComputer++;
				}
				
				viralComputers[x] = 1;
				
				break;
			case 2:
				scanf("%d", &x);
				
				x--;
				
				if (viralComputers[x] == 1)
				{
					numberViralComputer--;
				}
				
				viralComputers[x] = 0;
				
				break;
			case 3:
				printf("%d\n", n - numberViralComputer);
				
				break;
		}
	}
	
	return 0;
}

3. 메시지

아무리 복잡해 보이는 문제라도 다양한 시각으로 바라보고 이해할 수 있는 것이 문제 해결 능력이 뛰어나다는 것을 보여주는 것이다.

생각을 다르게 하면 문제의 답을 찾을 수도 있다는 것이다.

댓글