[BaekJoon] #25192 - 인사성 밝은 곰곰이 [Java][C++]
[BaekJoon] #25192 - 인사성 밝은 곰곰이 [Java][C++]
1. 아이디어
"ENTER" 이후 채팅을 친 유저들의 수를 구하면 되는 문제로 각 유저가 여러 번 채팅을 칠 수 있는데 이를 중복으로 세지 않아야 한다. 집합을 활용해서 채팅을 친 유저를 집합에 담다가 "ENTER"가 등장하면 집합의 크기를 카운팅해나가면 해결할 수 있다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = 입력값 n. C++는 트리 기반 set이라 시간 $O(N \log N)$)
3. 코드
풀이 [Java][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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Set<String> set = new HashSet<>();
int cnt = 0;
while (n-- > 0) {
String line = br.readLine();
if (line.equals("ENTER")) {
cnt += set.size();
set.clear();
} else {
set.add(line);
}
}
cnt += set.size();
System.out.println(cnt);
}
}
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
set<string> st;
int cnt = 0;
while (n--) {
string line;
cin >> line;
if (line == "ENTER") {
cnt += st.size();
st.clear();
} else {
st.insert(line);
}
}
cnt += st.size();
cout << cnt;
}
std::unordered_set의 경우 입력의 크기가 커서 성능 문제가 있어 std::set을 활용했다.
This post is licensed under CC BY 4.0 by the author.