Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Node {
- public $leaf;
- public $kids = array();
- function __construct($leaf) {
- $this->leaf = $leaf;
- }
- function childExists($childVal) {
- return (array_key_exists($childVal, $this->kids));
- }
- function addChild($childVal, $isLeaf) {
- $newNode = new Node($isLeaf);
- $this->kids[$childVal] = $newNode;
- return $this->kids[$childVal];
- }
- function getChild($childVal) {
- return $this->kids[$childVal];
- }
- function hasChilds() {
- return (!empty($this->kids));
- }
- function checkLeaf() {
- return $this->leaf;
- }
- }
- fscanf(STDIN, "%d", $numOfTestCases);
- for ($i = 0; $i < $numOfTestCases; $i++) { //Loop for reading test cases
- fscanf(STDIN, "%d", $numOfPhoneNumbers);
- $isConsistent = true;
- $startNode = new Node(false);
- for ($j = 0; $j < $numOfPhoneNumbers; $j++) { //Loop for reading phone numbers of each test case
- fscanf(STDIN, "%d", $newNumber);
- if ($isConsistent) { // Does not need to check new number if list is already inconsistent
- $numArr = str_split(strval($newNumber)); // Spitting new number into array
- $currNode = $startNode;
- $isConsistent = true;
- foreach ($numArr as $k => $numstr) { // Loop for checking each digit
- if ($currNode->checkLeaf()) { // If current node is a leaf
- $isConsistent = false;
- break;
- } else {
- if (!$currNode->childExists($numstr)) {
- if ($k == count($numArr)-1) {
- $currNode = $currNode->addChild($numstr, true);
- } else {
- $currNode = $currNode->addChild($numstr, false);
- }
- } else {
- $currNode = $currNode->getChild($numstr);
- }
- }
- }
- if ($currNode->hasChilds()) $isConsistent = false;
- }
- }
- $newAnswer = ($isConsistent) ? "YES" : "NO";
- $ansString = ($i == 0) ? $newAnswer : $ansString."\n".$newAnswer;
- }
- fwrite(STDOUT, $ansString);
- exit(0);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment