※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 13244번 문제인 Tree이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/13244 

 

13244번: Tree

For each graph, a single line with “tree” if the graph represents a tree or “graph“ otherwise.

www.acmicpc.net

노드 N개가 있는 그래프의 경우, 에지가 N-1개이고 연결그래프이면 주어진 그래프는 tree임을 이용해 문제를 해결하자.

 

주어진 그래프가 연결그래프임을 확인하는 쉬운 방법중 하나는 disjoint set 자료구조를 이용하는 것이다. 

 

아래는 제출한 소스코드이다.

#include <iostream>
using namespace std;

int N, K;
int arr[1001];

int findf(int x) {
	if (arr[x] == x) return x;
	else return arr[x] = findf(arr[x]);
}

void solve() {
	cin >> N;
	for (int i = 1; i <= N; i++) arr[i] = i;
	cin >> K;
	if (K == N - 1) {
		bool chk = 1;
		while (K--) {
			int x, y; cin >> x >> y;
			x = findf(x), y = findf(y);
			if (x == y) chk = 0;
			arr[y] = x;
		}

		if (chk) cout << "tree\n";
		else cout << "graph\n";
	}
	else {
		cout << "graph\n";
		while (K--) cin >> N >> N;
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int T; cin >> T;
	while (T--) solve();
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 13212 // C++] Random  (0) 2023.06.02
[BOJ 13211 // C++] Passport Checking  (0) 2023.06.01
[BOJ 13243 // C++] Non-decreasing subsegment  (0) 2023.05.30
[BOJ 13220 // C++] Secret  (0) 2023.05.29
[BOJ 13219 // C++] Trains  (0) 2023.05.28

+ Recent posts