[백준 27330] 点数 (Score) (C#, C++) - soo:bak
작성일 :
문제 링크
설명
점수를 누적하다가 특정 값에 도달하면 0으로 리셋하는 게임의 최종 점수를 구하는 문제입니다.
접근법
리셋 조건이 되는 값들을 해시셋에 저장하여 빠르게 조회할 수 있도록 합니다. 점수에 각 값을 순서대로 더한 뒤, 현재 점수가 리셋 조건에 해당하면 0으로 초기화합니다. 모든 값을 처리한 후 최종 점수를 출력합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var n = int.Parse(Console.ReadLine()!);
var a = Array.ConvertAll(Console.ReadLine()!.Split(), int.Parse);
_ = Console.ReadLine();
var b = new HashSet<int>(Array.ConvertAll(Console.ReadLine()!.Split(), int.Parse));
var score = 0;
for (var i = 0; i < n; i++) {
score += a[i];
if (b.Contains(score)) score = 0;
}
Console.WriteLine(score);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
vi a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int m; cin >> m;
unordered_set<int> b;
b.reserve(m * 2);
for (int i = 0; i < m; i++) {
int x; cin >> x;
b.insert(x);
}
int score = 0;
for (int i = 0; i < n; i++) {
score += a[i];
if (b.count(score)) score = 0;
}
cout << score << "\n";
return 0;
}