about summary refs log tree commit diff
path: root/usth/MATH2.3/3/graph-is-tree.cc
diff options
context:
space:
mode:
authorNguyễn Gia Phong <vn.mcsinyx@gmail.com>2020-01-14 18:29:11 +0700
committerNguyễn Gia Phong <vn.mcsinyx@gmail.com>2020-01-14 18:29:11 +0700
commita3dd2581ed4847670f81157091016c14ca18803d (patch)
tree3362ab15de119f1e75799f58715b7683e6bfd6ca /usth/MATH2.3/3/graph-is-tree.cc
parent65b8ebda4c47fa27ac28899fb2b29097f445b6df (diff)
downloadcp-a3dd2581ed4847670f81157091016c14ca18803d.tar.gz
[usth/MATH2.3] Mathemate Discretely
Diffstat (limited to 'usth/MATH2.3/3/graph-is-tree.cc')
-rw-r--r--usth/MATH2.3/3/graph-is-tree.cc56
1 files changed, 56 insertions, 0 deletions
diff --git a/usth/MATH2.3/3/graph-is-tree.cc b/usth/MATH2.3/3/graph-is-tree.cc
new file mode 100644
index 0000000..f79564d
--- /dev/null
+++ b/usth/MATH2.3/3/graph-is-tree.cc
@@ -0,0 +1,56 @@
+#include <iostream>
+#include <unordered_map>
+#include <unordered_set>
+#include <vector>
+
+using namespace std;
+
+int
+main ()
+{
+  size_t n;
+  int b;
+  unordered_map<size_t, unordered_set<size_t>> edges;
+
+  int m = 0;
+  cin >> n;
+  for (size_t i = 0; i < n; ++i)
+    for (size_t j = 0; j < n; ++j)
+      {
+        cin >> b;
+        if (!b || i > j)
+          continue;
+        edges[i].insert (j);
+        edges[j].insert (i);
+        m++;
+      }
+
+  if (n - m - 1)
+    {
+      cout << "no" << endl;
+      return 0;
+    }
+
+  unordered_set<size_t> s;
+  int count = -1;
+  for (auto const& [v, p] : edges)
+    {
+      if (s.count (v))
+        continue;
+      count++;
+      vector<size_t> lifo {v};
+      while (!lifo.empty ())
+        {
+          size_t u = lifo.back ();
+          lifo.pop_back ();
+          if (s.count (u))
+            continue;
+          s.insert (u);
+          for (auto const& w : edges[u])
+            if (!s.count (w))
+              lifo.push_back (w);
+        }
+    }
+
+  cout << (count ? "no" : "yes") << endl;
+}