백준 알고리즘(C++)

백준 13244번 Tree ( C++ )

coding232624 2024. 8. 30. 11:58

문제

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

 

해설

기본적인 트리의 개념을 알고 있는지 물어보는 문제

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
 
using namespace std;
 
int t, n, m, node1, node2, visited[1004];
vector<int> edge[1004];
 
void bfs(int num)
{
  visited[num] = 1;
  queue<int> q;
  q.push(num);
  while (q.size())
  {
    num = q.front();
    q.pop();
    for (int i : edge[num])
    {
      if (!visited[i])
      {
        visited[i] = 1;
        q.push(i);
      }
    }
  }
}
 
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> t;
 
  for (int i = 0; i < t; i++)
  {
    cin >> n >> m;
    for (int j = 0; j < m; j++)
    {
      cin >> node1 >> node2;
      edge[node1].push_back(node2);
      edge[node2].push_back(node1);
    }
    if (n - 1 == m)
    {
      bfs(1);
      int flag = 0;
      for (int i = 1; i <= n; i++)
      {
        if (!visited[i] && flag == 0)
        {
          cout << "graph" << '\n';
          flag = 1;
        }
        edge[i].clear();
      }
      if (flag == 0)
      {
        cout << "tree" << "\n";
      }
    }
    else
    {
      cout << "graph" << '\n';
      for (int i = 1; i <= n; i++)
      {
        edge[i].clear();
      }
    }
    fill(&visited[0], &visited[1004], 0);
  }
}
cs

 

'백준 알고리즘(C++)' 카테고리의 다른 글

백준 14405번 피카츄 ( C++ )  (0) 2024.09.01
백준 5430번 AC ( C++ )  (0) 2024.08.31
백준 14391번 종이 조각 ( C++ )  (0) 2024.08.30
백준 11723번 집합 ( C++ )  (0) 2024.08.30
백준 2234번 성곽 ( C++ )  (0) 2024.08.29