CSES - Flight Discount

Authors: Kai Wang, Stanley Zhong, Maggie Liu, Kevin Sheng

Table of Contents

Solution 1Solution 2

Solution 1

Say we use the discount coupon on the edge between cities A and B.

There are two cases: we can go from 1ABN1\rightarrow A\rightarrow B\rightarrow N, or 1BAN1\rightarrow B\rightarrow A\rightarrow N. We need to know the distance between 11 and AA, and NN and BB.

We can use Dijkstra's to compute the distance from 11 and NN to every vertex. Then our answer is minABdist1[A]+c(A,B)+distN[B]\min\limits_{A\rightarrow B} \texttt{dist1}[A]+c(A,B)+\texttt{distN}[B], where c(A,B)c(A,B) is the cost to travel from city AA to city BB after applying the coupon to that flight, dist1[A]\texttt{dist1}[A] is the cost to travel from city 11 to city AA and distN[B]\texttt{distN}[B] is the cost to travel from city BB to city NN.

Java

import java.io.*;
import java.util.*;
public class FlightDiscount {
static class Flight {
int to;
long cost;
Flight(int v, long wt) {
this.to = v;
this.cost = wt;

C++

#include <iostream>
#include <queue>
#include <vector>
using std::cout;
using std::endl;
using std::pair;
using std::vector;
/**

Solution 2

Alternatively, we can run Dijkstra's and modify our distance array slightly to track whether the discount has been used or not.

dist[i][false]\texttt{dist}[i][\texttt{false}] will represent the shortest distance from the start node to node ii, without using the discount. dist[i][true]\texttt{dist}[i][\texttt{true}] will represent the shortest distance after using the discount.

C++

#include <iostream>
#include <queue>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main() {
int city_num;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!