fork download
  1. <?php
  2. class DSU {
  3. private $sz, $par;
  4.  
  5. public function __construct($n) {
  6. $this->sz = array_fill(0, $n, 1);
  7. $this->par = range(0, $n - 1);
  8. }
  9.  
  10. public function getPar($u) {
  11. if ($u == $this->par[$u]) {
  12. return $u;
  13. }
  14. return $this->par[$u] = $this->getPar($this->par[$u]);
  15. }
  16.  
  17. public function connect($u, $v) {
  18. $u = $this->getPar($u);
  19. $v = $this->getPar($v);
  20. if ($u != $v) {
  21. if ($this->sz[$u] < $this->sz[$v]) {
  22. list($u, $v) = array($v, $u);
  23. }
  24. $this->sz[$u] += $this->sz[$v];
  25. $this->par[$v] = $u;
  26. }
  27. }
  28. }
  29.  
  30. function unique(&$s) {
  31. }
  32.  
  33. $dsu = new DSU(26);
  34.  
  35. fscanf(STDIN, "%d", $n);
  36. $used = array_fill(0, 26, false);
  37.  
  38. for ($i = 0; $i < $n; $i++) {
  39. $s = str_split(trim(fgets(STDIN)));
  40. sort($s);
  41. unique($s);
  42. foreach ($s as $ch) {
  43. $used[ord($ch) - ord('a')] = true;
  44. }
  45. $k = count($s);
  46. for ($j = 0; $j < $k - 1; $j++) {
  47. $dsu->connect(ord($s[$j]) - ord('a'), ord($s[$j + 1]) - ord('a'));
  48. }
  49. }
  50.  
  51. $parents = [];
  52. for ($i = 0; $i < 26; $i++) {
  53. if ($used[$i]) {
  54. $parents[] = $dsu->getPar($i);
  55. }
  56. }
  57. sort($parents);
  58. unique($parents);
  59. echo count($parents) . "\n";
  60.  
Success #stdin #stdout 0.03s 26000KB
stdin
4
a
b
ab
d
stdout
2