Advertisement
kevinsf90

Quora Nearby - CodeSprint2

Jan 8th, 2012
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. # Quora Nearby problem for CodeSprint2
  2. # Scored 9/10 test cases before Time Limit Reached disqualify the last test case... =/
  3. # Author: Kevin Tham
  4.  
  5. def solve(topicsIndex, questions, queries):
  6.     # Process the queries
  7.     for query in queries:
  8.         distances = []
  9.         if query[0] == 't':
  10.             # Calculate distance to all topics
  11.             for topic in topicsIndex.values():
  12.                 distances.append((topic[0], specialDist(query[2], query[3], topic[1], topic[2])+tiebreak(topic[0])))
  13.         elif query[0] == 'q':
  14.             # Use dictionary to cache distance, as we move from question to question
  15.             topicDists = {}
  16.  
  17.             # Find minimum distances for each question
  18.             for question in questions:
  19.                 qTopics = []
  20.                 for tid in question[1]:
  21.                     # If we did not calculate the distance, do so now
  22.                     if not topicDists.has_key(tid) :
  23.                         # Cache distance into the dictionary
  24.                         topicDists[tid] = specialDist(query[2], query[3], topicsIndex[tid][1], topicsIndex[tid][2])
  25.                     qTopics.append((topicDists[tid],tid))
  26.                 if len(qTopics)>0:
  27.                     distances.append((question[0], min(qTopics)[0]+tiebreak(question[0])))
  28.         distances.sort(key=lambda x:x[1])
  29.         results = map(lambda x: x[0],distances[:query[1]])
  30.         print'%s' % ' '.join(map(str, results))
  31.  
  32. def tiebreak(idNum):
  33.     # Using decimal to hold tiebreak value
  34.     return 1.0/(idNum+1.0)
  35.  
  36. def specialDist(x1,y1,x2,y2):
  37.     return ((x2-x1)**2 + (y2-y1)**2)
  38.    
  39. def main():
  40.     T, Q, N = map(int,raw_input().split())
  41.     topicsIndex = {}
  42.     questions = []
  43.     queries = []
  44.     for t in xrange(T):
  45.         args = raw_input().split()
  46.         tid = int(args[0])
  47.         topicsIndex[tid] = ((tid, float(args[1]),float(args[2])))
  48.     for q in xrange(Q):
  49.         args = raw_input().split()
  50.         questions.append((int(args[0]), map(float, args[2:])))
  51.     for q in xrange(N):
  52.         args = raw_input().split()
  53.         queries.append((args[0], int(args[1]), float(args[2]), float(args[3])))
  54.     solve(topicsIndex, questions, queries)
  55.        
  56. if __name__ == '__main__':
  57.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement