ARC037 B - バウムテスト

Calendar Clock iconCalendar Clock icon


Table of contents

# Problem

# Input

u1v1u_1 v_1
u2v2u_2 v_2
uMvMu_M v_M

  • NN - The number of vertices
  • MM - The number of undirected edges
  • uiviu_i v_i - Edge which connects uiu_i and viv_i

# Output

Report the number of trees.

A tree is either

    1. A connected graph which has only 1 vertex.
    1. A connected graph which doesn't have a cycle.

# Explanation

For each vertex, visit it if you haven't visited it yet.
If the vertex doen't have any edge, it's a tree.
If it has edges, visit its neighbor vertices.
If a visited vertex is found, it's a cycle, not a tree.
If any visited vertex is not found to the end, it's a tree.

You visit a vertex just once, so the time complexity is O(N)O(N).

# Time complexity


# Solution

// C++ 14
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <math.h>

#define ll long long
#define Int int
#define loop(x, start, end) for(Int x = start; x < end; x++)
#define loopdown(x, start, end) for(int x = start; x > end; x--)
#define rep(n) for(int x = 0; x < n; x++)
#define span(a,x,y) a.begin()+x,a.begin()+y
#define span_all(a) a.begin(),a.end()
#define len(x) (x.size())
#define last(x) (*(x.end()-1))

using namespace std;
#define MAX_N 100

Int N, M;
vector<Int> G[MAX_N];
vector<Int> done(MAX_N, false);

void input() {
  Int u,v;
  cin >> N >> M;

  while (cin >> u >> v) {

bool dfs_isTree(Int u, Int depth, Int parent) {
  done[u] = true;
  if (len(G[u]) == 0) return true;

  bool cycle = false;
  for (auto v: G[u]) {
    if (v == parent) continue;
    if (done[v]) return false;
    cycle |= !dfs_isTree(v, depth + 1, u);
  return !cycle;

void solve() {
  Int counter = 0;
  loop(u,0,N) {
    if (done[u]) continue;
    counter += dfs_isTree(u, 0, -1);
  cout << counter << endl;

int main(void) {
  return 0;

Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!

Offer jobs or contact me!