Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
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
Archives
Today
Total
관리 메뉴

dh-winternagi 님의 블로그

(4803) 트리 본문

백준 (C++)/Solve

(4803) 트리

dh-winternagi 2026. 4. 20. 15:10

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

단계별로 풀어보기

33단계(트리) 7번째

 

 

 

트리 여부를 확인하는 문제. 그래프를 순회하면서 이전 정점이 아니고 이미 방문한 정점과 이어져 있다면 사이클이 있다는 것이다.

 

 

 

#include <iostream>
#include <vector>
using namespace std;

void solve(int c, int n, int m){
  vector adj(n+1, vector<int> ());
  vector<bool> visited(n+1);
  int cnt= 0;
  bool istree= true;
  
  while(m--){
    int u, v;
    
    cin >> u >> v;
    
    adj[u].push_back(v);
    adj[v].push_back(u);
  }
  
  auto dfs= [&](auto self, int now, int prev) -> void {
    visited[now]= true;
    
    for(int next:adj[now]){
      if(next==prev)  continue;
      if(visited[next]){
        istree= false;
        continue;
      }
      
      self(self, next, now);
    }
  };
  
  for(int i=1;i<=n;i++){
    if(visited[i])  continue;
    
    istree= true;
    dfs(dfs, i, 0);
    cnt+= istree;
  }
  
  cout << "Case " << c << ": ";
  
  if(cnt==0)  cout << "No trees.\n";
  else if(cnt==1)  cout << "There is one tree.\n";
  else  cout << "A forest of " << cnt << " trees.\n";
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  
  for(int i=1;;i++){
    int n, m;
    
    cin >> n >> m;
    
    if(!n)  break;
    
    solve(i, n, m);
  }
  
  return 0;
}

'백준 (C++) > Solve' 카테고리의 다른 글

(1976) 여행 가자  (0) 2026.04.20
(1717) 집합의 표현  (0) 2026.04.20
(5639) 이진 검색 트리  (0) 2026.04.20
(2263) 트리의 순회  (0) 2026.04.20
(1991) 트리 순회  (0) 2026.04.20