結果

問題 No.583 鉄道同好会
ユーザー 👑 emthrmemthrm
提出日時 2021-09-23 01:24:41
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 126 ms / 2,000 ms
コード長 2,054 bytes
コンパイル時間 906 ms
コンパイル使用メモリ 87,180 KB
実行使用メモリ 11,160 KB
最終ジャッジ日時 2023-09-18 19:45:55
合計ジャッジ時間 2,090 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 2 ms
4,376 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 2 ms
4,380 KB
testcase_10 AC 2 ms
4,376 KB
testcase_11 AC 14 ms
4,380 KB
testcase_12 AC 19 ms
4,780 KB
testcase_13 AC 19 ms
4,984 KB
testcase_14 AC 19 ms
4,824 KB
testcase_15 AC 24 ms
5,012 KB
testcase_16 AC 43 ms
6,400 KB
testcase_17 AC 53 ms
6,764 KB
testcase_18 AC 126 ms
11,160 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>

struct EulerianTrailInUndirectedGraph {
  std::vector<int> trail;

  EulerianTrailInUndirectedGraph(const int n) : n(n), graph(n), is_visited(n) {}

  void add_edge(const int u, const int v) {
    graph[u].emplace_back(v, graph[v].size());
    graph[v].emplace_back(u, graph[u].size() - 1);
  }

  bool build(int s = -1) {
    trail.clear();
    int odd_deg = 0, edge_num = 0;
    for (int i = 0; i < n; ++i) {
      if (graph[i].size() & 1) {
        ++odd_deg;
        if (s == -1) {
          s = i;
        }
      }
      edge_num += graph[i].size();
    }
    if (s == -1) {
      for (int i = 0; i < n; ++i) {
        if (!graph[i].empty()) {
          s = i;
          break;
        }
      }
      if (s == -1) {
        assert(edge_num == 0);
        trail.emplace_back(0);
        return true;
      }
    }
    for (int i = 0; i < n; ++i) {
      is_visited[i].assign(graph[i].size(), false);
    }
    if (odd_deg == 0 || (odd_deg == 2 && (graph[s].size() & 1))) {
      dfs(s);
      if (trail.size() == (edge_num >> 1) + 1) {
        std::reverse(trail.begin(), trail.end());
        return true;
      }
      trail.clear();
    }
    return false;
  }

private:
  struct Edge {
    int dst, rev;
    Edge(const int dst, const int rev) : dst(dst), rev(rev) {}
  };

  const int n;
  std::vector<std::vector<Edge>> graph;
  std::vector<std::vector<int>> is_visited;

  void dfs(const int ver) {
    const int deg = graph[ver].size();
    for (int i = 0; i < deg; ++i) {
      if (!is_visited[ver][i]) {
        const int dst = graph[ver][i].dst;
        is_visited[ver][i] = is_visited[dst][graph[ver][i].rev] = true;
        dfs(dst);
      }
    }
    trail.emplace_back(ver);
  }
};

int main() {
  int n, m;
  std::cin >> n >> m;
  EulerianTrailInUndirectedGraph eulerian_trail(n);
  while (m--) {
    int sa, sb;
    std::cin >> sa >> sb;
    eulerian_trail.add_edge(sa, sb);
  }
  std::cout << (eulerian_trail.build() ? "YES\n" : "NO\n");
  return 0;
}
0