A Dynamic Programming Technique for Classifying Trajectories