Finding a cheap ight Imagine you graduated and got a job at stingyights.com. You
ID: 3889115 • Letter: F
Question
Finding a cheap ight
Imagine you graduated and got a job at stingyights.com. Your task is to design an algorithm for nding cheap ights. You are given a list of n cities, and a list of m ights between them. For each ight i, you are given its departure city xi, its destination city yi, its departure time ti, its duration di, and its cost ci. So ight i departs from city xi at time ti, arrives at city yi at time ti + di, and costs ci dollars.
Design an algorithm that given a pair of cities a, b, computes the cheapest possible route (i.e. sequence of ights) that starts at a at time 0, and ends at b at time at most T . The running time of your algorithm should be polynomial in n and m (e.g. O(n10m5)).
Hint: Express the above problem as shortest-path computation in some graph.
Explanation / Answer
struct ticket { int src; int dst; }; int get_airport_bucket_index( int airport_code, int discriminating_bit) { return (airport_code & discriminating_bit)==discriminating_bit ? 1 : 0; } void find_trip_endpoints(const ticket *tickets, size_t ticket_count, int *out_src, int *out_dst) { int xor_residual= 0; for (const ticket *current_ticket= tickets, *end_ticket= tickets + ticket_count; current_ticket!=end_ticket; ++current_ticket) { xor_residual^= current_ticket->src; xor_residual^= current_ticket->dst; } // now xor_residual will be equal to the starting airport xor ending airport // since starting airport!=ending airport, they have at least one bit that is not in common // int discriminating_bit= xor_residual & (-xor_residual); assert(discriminating_bit!=0); int airport_codes[2]= { xor_residual, xor_residual }; int src_count[2]= { 0, 0 }; int dst_count[2]= { 0, 0 }; for (const ticket *current_ticket= tickets, *end_ticket= tickets + ticket_count; current_ticket!=end_ticket; ++current_ticket) { int src_index= get_airport_bucket_index(current_ticket->src, discriminating_bit); airport_codes[src_index]^= current_ticket->src; src_count[src_index]+= 1; int dst_index= get_airport_bucket_index(current_ticket->dst, discriminating_bit); airport_codes[dst_index]^= current_ticket->dst; dst_count[dst_index]+= 1; } assert((airport_codes[0]^airport_codes[1])==xor_residual); assert(abs(src_count[0]-dst_count[0])==1); // all airports with the bit set/unset will be accounted for as well as either the source or destination assert(abs(src_count[1]-dst_count[1])==1); assert((src_count[0]-dst_count[0])==-(src_count[1]-dst_count[1])); int src_index= src_count[0]-dst_count[0]Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.