๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 30803_์ˆ˜๋„๊ผญ์ง€

๋ฟŒ์•ผ._. 2024. 7. 9. 13:34
๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/30803)

< ์ˆ˜๋„๊ผญ์ง€ >

 

๋ฌธ์ œ ํ’€์ด 

 

์ˆ˜๋„๊ผญ์ง€๊ฐ€ ์ž ๊ฒผ์„ ๋•Œ์™€ ์—ด๋ ธ์„ ๋•Œ๋ฅผ ๊ตฌ๋ถ„ํ•˜์—ฌ ํƒฑํฌ์— ๋‹ด๊ธฐ๋Š” ๋ฌผ์˜ ์–‘์„ ๊ตฌํ•œ๋‹ค.

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class _30803_ { // ์ˆ˜๋„๊ผญ์ง€

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st;

		int N = Integer.parseInt(bf.readLine());
		int arr[] = new int[N + 1];
		boolean visited[] = new boolean[N + 1];

		long answer = 0;
		st = new StringTokenizer(bf.readLine());
		for (int i = 1; i < N + 1; i++) {
			arr[i] = Integer.parseInt(st.nextToken());
			answer += arr[i];
		}
		bw.write(answer + "\n");

		int Q = Integer.parseInt(bf.readLine());
		for (int i = 0; i < Q; i++) {
			st = new StringTokenizer(bf.readLine());

			int num = Integer.parseInt(st.nextToken());
			if (num == 1) {
				int temp = Integer.parseInt(st.nextToken());
				int x = Integer.parseInt(st.nextToken());
				if (visited[temp]) {
					arr[temp] = x;
				} else {
					answer -= arr[temp];
					arr[temp] = x;
					answer += arr[temp];
				}
			} else {
				int x = Integer.parseInt(st.nextToken());
				if (!visited[x]) {
					visited[x] = true;
					answer -= arr[x];
				} else {
					visited[x] = false;
					answer += arr[x];
				}
			}
			bw.write(answer + "\n");
		}
		bw.flush();
	}
}
๋ณ€์ˆ˜)
N : ์ˆ˜๋„๊ผญ์ง€์˜ ์ˆ˜
arr : ์ˆ˜๋„๊ผญ์ง€์—์„œ ๋‚˜์˜ค๋Š” ๋ฌผ์˜ ์–‘
visited : ์ˆ˜๋„๊ผญ์ง€ ์—ด๋ ธ๋Š”์ง€ ์—ฌ๋ถ€
answer : 1๋ถ„ ๋™์•ˆ ํƒฑํฌ์— ๋‹ด๊ธฐ๋Š” ๋ฌผ์˜ ์–‘
Q : ์กฐ์ž‘์˜ ์ˆ˜
num : ์กฐ์ž‘ ๋ฒˆํ˜ธ

 

์ˆ˜๋„๊ผญ์ง€์˜ ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ์ˆ˜๋„๊ผญ์ง€์˜ ์ˆ˜๋งŒํผ ์ˆ˜๋„๊ผญ์ง€์—์„œ ๋‚˜์˜ค๋Š” ๋ฌผ์˜ ์–‘์„ ์ž…๋ ฅ๋ฐ›์•„ arr์— ์ €์žฅํ•œ๋‹ค. ์กฐ์ž‘์˜ ์ˆ˜ Q๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ์กฐ์ž‘์˜ ์ˆ˜๋งŒํผ ์กฐ์ž‘์„ ์ž…๋ ฅ๋ฐ›์•„ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

1) ์กฐ์ž‘ ๋ฒˆํ˜ธ๊ฐ€ 1์ด๋ผ๋ฉด ์ˆ˜๋„๊ผญ์ง€ ๋ฒˆํ˜ธ temp์™€ ๋ฌผ์˜ ์–‘ x๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ๋งŒ์•ฝ temp๋ฒˆ ์ˆ˜๋„๊ผญ์ง€๊ฐ€ ์ž ๊ฒจ์žˆ๋‹ค๋ฉด ๋ฌผ์˜ ์–‘๋งŒ ๋ฐ”๊พธ๊ณ , ์—ด๋ ค์žˆ๋‹ค๋ฉด answer์— ์›๋ž˜ ๋ฌผ์˜ ์–‘์„ ๋นผ์ฃผ๊ณ  x๋ฅผ ๋”ํ•œ๋‹ค.

2) ์กฐ์ž‘ ๋ฒˆํ˜ธ๊ฐ€ 2๋ผ๋ฉด ์ˆ˜๋„๊ผญ์ง€ ๋ฒˆํ˜ธ x๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ๋งŒ์•ฝ x๋ฒˆ ์ˆ˜๋„๊ผญ์ง€๊ฐ€ ์—ด๋ ค์žˆ๋‹ค๋ฉด ์ž ๊ทธ๊ณ  answer์— ๊ทธ ๊ฐ’์„ ๋นผ์ค€๋‹ค. ๋งŒ์•ฝ ์ž ๊ฒจ์žˆ๋‹ค๋ฉด ์—ด๊ณ  answer์— ๊ทธ ๊ฐ’์„ ๋”ํ•œ๋‹ค.

3) answer์„ ์ถœ๋ ฅํ•œ๋‹ค.