๋ฌธ์
6416๋ฒ: ํธ๋ฆฌ์ธ๊ฐ?
ํธ๋ฆฌ๋ ๊ต์ฅํ ์ ์๋ ค์ง ์๋ฃ ๊ตฌ์กฐ์ด๋ค. ํธ๋ฆฌ๋ฅผ ๋ง์กฑํ๋ ์๋ฃ ๊ตฌ์กฐ๋ ๋น์ด ์๊ฑฐ๋(๋ ธ๋์ ๊ฐ์๊ฐ 0๊ฐ), ๋ ธ๋์ ๊ฐ์๊ฐ 1๊ฐ ์ด์์ด๊ณ ๋ฐฉํฅ ๊ฐ์ ์ด ์กด์ฌํ๋ฉฐ ๋ค์๊ณผ ๊ฐ์ ์กฐ๊ฑด์ ๋ง์กฑํด์ผ ํ๋ค.
www.acmicpc.net
์ฝ๋
#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include <queue>
#define MAX 101
using namespace std;
vector<int>indegree[MAX + 1];
unordered_map<int, int> outdegree; // node, cnt
unordered_set<int> node;
int edge_cnt = 0;
int remove_leaf() {
queue<int> q;
int remove_cnt = 0;
for (auto cur : node) {
if (outdegree[cur] == 0 && indegree[cur].size() == 1) {
q.push(cur);
}
}
while (!q.empty()) {
remove_cnt++;
int nod = q.front();
q.pop();
if (indegree[nod].size() == 1) {
vector<int> nexts;
for (auto next : indegree[nod]) {
nexts.push_back(next);
}
for (auto next : nexts) {
outdegree[next]--;
if (outdegree[next] == 0 && indegree[next].size() == 1) {
q.push(next);
}
}
}
}
return remove_cnt;
}
void init() {
outdegree.clear();
node.clear();
for (int i = 0; i < MAX; i++) indegree[i].clear();
edge_cnt = 0;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int a, b;
int num = 1;
while (cin >> a >> b) {
if (a == -1 && b == -1) break;
else if (a == 0 && b == 0) {
int leaf_cnt = remove_leaf();
if (node.size() == 0 || node.size() == leaf_cnt + 1) cout << "Case " << num << " is a tree."<<'\n';
else cout << "Case " << num << " is not a tree." << '\n';
num++;
init();
}
else {
edge_cnt++;
if (a != b) outdegree[a]++;
indegree[b].push_back(a);
node.insert(a);
node.insert(b);
}
}
}
ํ์ด
ํด๊ฒฐ ์์ด๋์ด๋ ๋ฆฌํ ๋ ธ๋๋ฅผ ์ง์๊ฐ๋ ๋ฐฉ์์ผ๋ก ํด๊ฒฐํ์ต๋๋ค.
์ฐธ๊ณ : https://hanbi97.tistory.com/337
๋ง์ฝ ํธ๋ฆฌ์ผ ๊ฒฝ์ฐ์๋ ๋ฆฌํ ๋ ธ๋๋ฅผ ๊ณ์ ์ ๊ฑฐํด ๊ฐ์ ๋ ๋ฃจํธ ๋ ธ๋๋ง ๋จ๊ฒ ๋ ๊ฒ์ด๊ณ , ์ต์ข ์ ์ผ๋ก ์ง์ด ๋ ธ๋ ๊ฐ์ + 1(๋ฃจํธ ๋ ธ๋) = ์ด ๋ ธ๋ ๊ฐ์ ์ผ ๋ tree๊ฐ ๋ง๋ค ๋ฅผ ์ถ๋ ฅํ๋ ๋ฐฉ์์ผ๋ก ํ์์ต๋๋ค.
'Algorithm ๐ง๐ปโ๐ป > ๋ฐฑ์ค(BOJ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค,c++] 1967๋ฒ - ํธ๋ฆฌ์ ์ง๋ฆ (0) | 2022.07.11 |
---|---|
[๋ฐฑ์ค,c++] 3584๋ฒ - ๊ฐ์ฅ ๊ฐ๊น์ด ๊ณตํต ์กฐ์ (0) | 2022.07.11 |
[๋ฐฑ์ค,c++] 14675๋ฒ - ๋จ์ ์ ๊ณผ ๋จ์ ์ (0) | 2022.06.30 |
[๋ฐฑ์ค,c++] 1068๋ฒ - ํธ๋ฆฌ (0) | 2022.06.21 |
[๋ฐฑ์ค,c++] 5539๋ฒ - ์ด์ง ๊ฒ์ ํธ๋ฆฌ (0) | 2022.06.21 |
[๋ฐฑ์ค,c++] 9934๋ฒ - ์์ ์ด์ง ํธ๋ฆฌ (0) | 2022.06.21 |
๋๊ธ