HDU-1116.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <array>
  2. #include <iostream>
  3. #include <numeric>
  4. #include <string>
  5. using namespace std;
  6. struct DSU {
  7. array<int, 26> p{};
  8. DSU() { iota(p.begin(), p.end(), 0); }
  9. int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }
  10. void unite(int a, int b) {
  11. a = find(a); b = find(b);
  12. if (a != b) p[a] = b;
  13. }
  14. };
  15. int main() {
  16. ios::sync_with_stdio(false);
  17. cin.tie(nullptr);
  18. int t;
  19. cin >> t;
  20. while (t--) {
  21. int n;
  22. cin >> n;
  23. array<int, 26> in{}, out{};
  24. array<bool, 26> seen{};
  25. DSU dsu;
  26. for (int i = 0; i < n; ++i) {
  27. string s;
  28. cin >> s;
  29. int u = s.front() - 'a';
  30. int v = s.back() - 'a';
  31. ++out[u]; ++in[v];
  32. seen[u] = seen[v] = true;
  33. dsu.unite(u, v);
  34. }
  35. int root = -1;
  36. bool ok = true;
  37. for (int v = 0; v < 26; ++v) if (seen[v]) {
  38. if (root == -1) root = dsu.find(v);
  39. else if (dsu.find(v) != root) ok = false;
  40. }
  41. int plus = 0, minus = 0;
  42. for (int v = 0; v < 26; ++v) {
  43. int diff = out[v] - in[v];
  44. if (diff == 1) ++plus;
  45. else if (diff == -1) ++minus;
  46. else if (diff != 0) ok = false;
  47. }
  48. ok = ok && ((plus == 0 && minus == 0) || (plus == 1 && minus == 1));
  49. cout << (ok ? "Ordering is possible.\n"
  50. : "The door cannot be opened.\n");
  51. }
  52. }