[BaekJoon] 26069번 - 붙임성 좋은 총총이 [Java][C++]
[BaekJoon] 26069번 - 붙임성 좋은 총총이 [Java][C++]
1. 문제 풀이
무지개 댄스를 추는 사람을 만나면 무지개 댄스를 추지 않는 사람도 무지개 댄스를 추게 된다. 집합 자료구조를 활용하면 간단하게 해결할 수 있는데 무지개 댄스를 추는 사람을 집합에 넣고 각 사람에 대해 옆 사람이 무지개 댄스를 추면 해당 사람도 무지개 댄스를 추게 처리하면 된다.
2. 코드
1. 풀이 [Java]
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());
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
String name1 = st.nextToken();
String name2 = st.nextToken();
if (set.contains(name1)) set.add(name2);
if (set.contains(name2)) set.add(name1);
}
System.out.println(set.size());
}
}
2. 풀이 [C++]
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(false);
cin.tie(nullptr);
unordered_set<string> st;
st.insert("ChongChong");
int n;
cin >> n;
for (int i = 0; i < n; i++) {
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.