fork download
  1. import sys
  2.  
  3.  
  4. def read_n_integers(n: int) -> list[int]:
  5. """Reads stream inputs until exactly `n` integers are collected."""
  6. numbers = []
  7. # Reads tokens continuously from standard input
  8. for line in sys.stdin:
  9. numbers.extend(map(int, line.split()))
  10. if len(numbers) >= n:
  11. break
  12. return numbers[:n]
  13.  
  14.  
  15. def match_pairs(wants_taller: list[int], wants_shorter: list[int]) -> int:
  16. """Greedily pairs individuals who want taller partners with those who want shorter partners.
  17.  
  18. wants_taller: Heights of people needing a taller partner.
  19. wants_shorter: Heights of people needing a shorter partner.
  20. """
  21. wants_taller.sort()
  22. wants_shorter.sort()
  23.  
  24. pairs_count = 0
  25. taller_idx = 0
  26. shorter_idx = 0
  27.  
  28. while taller_idx < len(wants_taller) and shorter_idx < len(wants_shorter):
  29. # Check if the person expecting a shorter partner is taller than the required height
  30. if wants_shorter[shorter_idx] > wants_taller[taller_idx]:
  31. pairs_count += 1
  32. taller_idx += 1
  33. shorter_idx += 1
  34. else:
  35. # Person wanting a shorter partner is too short; test the next taller candidate
  36. shorter_idx += 1
  37.  
  38. return pairs_count
  39.  
  40.  
  41. def main():
  42. input_data = sys.stdin.read().split()
  43. if not input_data:
  44. return
  45.  
  46. n = int(input_data[0])
  47.  
  48. # Extract all elements for group 1 (men) and group 2 (women)
  49. arr1 = [int(x) for x in input_data[1 : n + 1]]
  50. arr2 = [int(x) for x in input_data[n + 1 : 2 * n + 1]]
  51.  
  52. # Categorize Men
  53. men_want_taller = [x for x in arr1 if x > 0]
  54. men_want_shorter = [abs(x) for x in arr1 if x < 0]
  55.  
  56. # Categorize Women
  57. women_want_taller = [x for x in arr2 if x > 0]
  58. women_want_shorter = [abs(x) for x in arr2 if x < 0]
  59.  
  60. # Calculate valid pairs for both compatible configurations
  61. total_matches = match_pairs(
  62. women_want_taller, men_want_shorter
  63. ) + match_pairs(men_want_taller, women_want_shorter)
  64.  
  65. print(total_matches)
  66.  
  67.  
  68. if __name__ == "__main__":
  69. main()
Success #stdin #stdout 0.12s 14092KB
stdin
Standard input is empty
stdout
Standard output is empty