fork(1) download
  1. <?php
  2. // Discard the first input line! It's useless :)
  3. fgets(STDIN);
  4. $numbers = explode(' ', rtrim(fgets(STDIN)));
  5. $valuePerWife = array_sum($numbers) / 2;
  6.  
  7. // Taken from here: http://stackoverflow.com/a/13194803/603003
  8. // Credits to dAngelov: http://stackoverflow.com/users/955185/dangelov
  9. function pc_permute($items, $perms = array( )) {
  10. if (empty($items)) {
  11. $return = array($perms);
  12. } else {
  13. $return = array();
  14. for ($i = count($items) - 1; $i >= 0; --$i) {
  15. $newitems = $items;
  16. $newperms = $perms;
  17. list($foo) = array_splice($newitems, $i, 1);
  18. array_unshift($newperms, $foo);
  19. $return = array_merge($return, pc_permute($newitems, $newperms));
  20. }
  21. }
  22. return $return;
  23. }
  24.  
  25.  
  26. foreach (pc_permute($numbers) as $permutation) {
  27. $sum = 0;
  28. $rest = [];
  29.  
  30. for ($i=0; $i<count($permutation); $i++) {
  31. $sum += $permutation[$i];
  32. if ($sum == $valuePerWife) {
  33. $rest = array_slice($permutation, $i + 1);
  34. break;
  35. }
  36. }
  37.  
  38. if (array_sum($rest) == $valuePerWife) {
  39. echo implode(' ', array_slice($permutation, 0, $i + 1)), "\n";
  40. echo implode(' ', array_slice($permutation, $i + 1)), "\n";
  41. echo 'diff=0';
  42. }
  43. }
  44. exit('DIDNT FOUND ANY COMBINATION!');
Success #stdin #stdout 0.01s 20568KB
stdin
4
1 2 3 4
stdout
2 3
1 4
diff=0