[C++] 백준(BOJ) -13244 : 트리

인프런에 있는 큰돌님의 강의 10주완성 C++ 코딩테스트 | 알고리즘 코딩테스트를 듣고 정리한 필기입니다.

문제

BOJ - 13244 : 트리(링크)

One of the most important data structures in computer science is the tree. You already dealt with binary trees in the qualification round. This problem is about general trees.

Trees are the subset of graphs that have the following 3 properties:

It is connected: for every node you can reach every other node following edges. If an edge is removed, the graph is no longer connected. That is, some nodes cannot be reached anymore. When an edge is added between two existing nodes A and B, a cycle is created. There is a cycle if there is more than one way to go from A to B. Your task is to decide if a given graph is a tree or not.

입력

The first line will contain an integer T representing the number of graphs to check. There will be at most 10 graphs in each test case.

Each of the graph will be represented as follows:

The first line will contain an integer N with the number of nodes in the graph. The number of nodes will be between 1 and 1,000. The identifier of each node will be an integer from 1 to N.

The next line will contain an integer M with the number of edges in the graph. There will be at most 106 edges.

The next M lines will contain 2 integers A and B each. These are the two nodes connected by an edge.

The total sum of M in all test cases is at most 106.

출력

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

알고리즘

  1. 트리
  2. 그래프

풀이

  1. 트리의 특징
    1) N개의 노드를 가진 트리는 N-1 개의 간선을 가짐 (E = V - 1)
    2) DFS 1회에 모든 정점 방문 가능

코드

// BOJ - 13244: Tree
#include<bits/stdc++.h>
using namespace std;

int t, n, m, a, b, visited[1004], cnt;
vector<int> adj[1004];

void dfs(int here)
{
	visited[here] = 1;
	for (int there : adj[here])
	{
		if (!visited[there]) dfs(there);
	}
	return;
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> t;

	while (t--)
	{
		for (int i = 0; i < 1004; i++) adj[i].clear();
		fill(visited, visited + 1004, 0);
		cnt = 0;

		cin >> n >> m;
		for (int i = 0; i < m; i++)
		{
			cin >> a >> b;
			adj[a].push_back(b);
			adj[b].push_back(a);
		}

		for (int i = 1; i <= n; i++)
		{
			if (!visited[i])
			{
				dfs(i);
				cnt++;
			}
		}

		if (m == n - 1 && cnt == 1) cout << "tree" << '\n'; // 핵심
		else cout << "graph" << '\n';
	}
	return 0;
}

평가

  • 트리의 특징에 대해 아는 지 확인 하는 문제

© 2023 Jinsoo Lee. All rights reserved.

Powered by Hydejack v9.1.6