반응형
https://www.acmicpc.net/problem/21276
21276번: 계보 복원가 호석
석호촌에는 N 명의 사람이 살고 있다. 굉장히 활발한 성격인 석호촌 사람들은 옆 집 상도 아버님, 뒷집 하은 할머님 , 강 건너 유리 어머님 등 모두가 한 가족처럼 살아가고 있다. 그러던 어느 날
www.acmicpc.net
#include <bits/stdc++.h>
using namespace std;
int n, m, cnt=1;
map<string, int> dic;
string node[1001];
set<string> child[1001];
vector<int> adj[1001];
int degree[1001];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
node[cnt] = s;
dic[s] = cnt++;
}
cin >> m;
for (int i = 0; i < m; i++) {
string x, y;
cin >> x >> y;
adj[dic[y]].push_back(dic[x]);
degree[dic[x]]++;
}
queue<int> Q;
int K = 0;
vector<string> parent;
for (int i = 1; i <= n; i++) {
if (degree[i] == 0) {
K++;
Q.push(i);
parent.push_back(node[i]);
}
}
sort(parent.begin(), parent.end());
cout << K << '\n';
for (int i = 0; i < K; i++) {
cout << parent[i] << ' ';
}
cout << '\n';
while (!Q.empty()) {
int x = Q.front();
Q.pop();
for (auto nx : adj[x]) {
if (--degree[nx] == 0) {
//차수가 0이 되는 노드들만 x의 자식이다.
child[x].insert(node[nx]);
Q.push(nx);
}
}
}
for (auto x : dic) {
cout << x.first << ' ';
cout << child[x.second].size() << ' ';
for (auto c : child[x.second]) {
cout << c << ' ';
}
cout << '\n';
}
return 0;
}
반응형
'Algorithm > problem' 카테고리의 다른 글
백준 2848번 : 알고스팟어 - 위상정렬 C++ 코드 (0) | 2022.02.25 |
---|---|
백준 2056번: 작업 - 위상정렬 dp C++ 코드 (0) | 2022.02.25 |
백준 2529번: 부등호 - 백트래킹, 위상정렬 풀이 C++ (0) | 2022.02.25 |
백준 14442번 : 벽 부수고 이동하기 2 - BFS C++ (0) | 2022.02.24 |
백준 3665번 : 최종 순위 - 위상정렬 C++ 문제풀이 및 코드 (0) | 2022.02.24 |