Advertisement
Appendko

Tmp_phone

Aug 14th, 2020 (edited)
1,832
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. import numpy as np
  2. from io import StringIO
  3. from scipy.spatial import distance_matrix
  4.  
  5. input = """8 3 3
  6. 3 -2 10
  7. -1 1 15
  8. -1 4 10
  9. 3 2 20
  10. 4 3 20
  11. -3 -4 25
  12. 2 -3 15
  13. 0 2 10
  14. """
  15.  
  16. # Parse Input:
  17. f_inp = np.loadtxt(StringIO(input))
  18. n, p, d = f_inp[0]
  19. n = int(n) # number of cities should be integer
  20. p = int(p) # number of choosed cities should be integer
  21. xy = f_inp[1:, 0:2]
  22. pop = f_inp[1:, 2]
  23.  
  24. # Greedy Algorithm
  25. choice_lst = []
  26. sum_pop = 0
  27. distance = distance_matrix(xy, xy)
  28.  
  29. for i in range(p):
  30.     weighted_pop = (distance <= d)*pop
  31.     weighted_sum = weighted_pop.sum(axis=1)
  32.     choice = np.argmax(weighted_sum) # argmax gives the best choice: Greedy
  33.     covered = np.flatnonzero(weighted_pop[choice]) # cities in that choice
  34.     pop[covered] = 0 # Zeros the city already covered
  35.     sum_pop += weighted_sum[choice] # Total num pop
  36.     choice_lst.append(choice+1)
  37.  
  38. # Output
  39. choice_str = " ".join([str(x) for x in choice_lst])
  40. print("%s %d"%(choice_str,sum_pop))
  41.    
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement