kevinsf90

Subsequence Weighting - Codesprint 2

Jan 8th, 2012
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. # Subsequence Weighting Problem - CodeSprint2
  2. # O(n^2) solution (wasn't fast enough)
  3. # Author: Kevin Tham
  4.  
  5. def solve(numElements, sequence, weights):
  6.     W = {} # Contains the weights of increasing subsequences up to index j
  7.     maxWeighting = 0
  8.     for i in range(numElements):
  9.         w = weights[i]
  10.         W[i] = w
  11.         for j in reversed(range(0, i)):
  12.             isIncreasing = sequence[j] < sequence[i]
  13.             if (W[j] + w > W[i] and isIncreasing):
  14.                 W[i] = W[j] + w
  15.         if W[i] > maxWeighting:
  16.             maxWeighting = W[i]
  17.     return maxWeighting
  18.  
  19. def main():
  20.     testCases = int(raw_input())
  21.    
  22.     for testCase in range(testCases):
  23.         numElements = int(raw_input())
  24.         sequence = map(int, raw_input().split())
  25.         sequenceWeights = map(int, raw_input().split())
  26.         print solve(numElements, sequence, sequenceWeights)
  27.        
  28. if __name__ == '__main__':
  29.     main()
Add Comment
Please, Sign In to add comment