[BaekJoon] #26069 - 붙임성 좋은 총총이 [Java][C++]
[BaekJoon] #26069 - 붙임성 좋은 총총이 [Java][C++]
1. 아이디어
무지개 댄스를 추는 사람을 만나면 무지개 댄스를 추지 않는 사람도 무지개 댄스를 추게 된다. 집합 자료구조를 활용하면 간단하게 해결할 수 있는데 무지개 댄스를 추는 사람을 집합에 넣고 각 사람에 대해 옆 사람이 무지개 댄스를 추면 해당 사람도 무지개 댄스를 추게 처리하면 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = 입력값 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
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));
StringTokenizer st;
Set<String> set = new HashSet<>();
set.add("ChongChong");
int n = Integer.parseInt(br.readLine());
while (n-- > 0) {
st = new StringTokenizer(br.readLine());
String s1 = st.nextToken();
String s2 = st.nextToken();
if (set.contains(s1)) set.add(s2);
if (set.contains(s2)) set.add(s1);
}
System.out.println(set.size());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
unordered_set<string> st;
st.insert("ChongChong");
int n;
cin >> n;
while (n--) {
string s1, s2;
cin >> s1 >> s2;
if (st.count(s1)) st.insert(s2);
if (st.count(s2)) st.insert(s1);
}
cout << st.size();
}
This post is licensed under CC BY 4.0 by the author.