Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given a set of n cities (1..n) each with one jury member. There is a meeting point city 0 (Metropolis). There are m flights. Each flight: day d, departure city f, arrival city t, cost c. Exactly one of f or t is 0: i.e., flights are either from a city to Metropolis (inbound) or from Metropolis to a city (outbound). Flights are day flights (arrive same day, can't work on arrival/departure day). Need to bring all jury members to Metropolis, have them work together for k consecutive days, then send them back to home cities. The jury member can stay longer than k days. The cost is total tickets for all used flights (each jury member will take one inbound flight to Metropolis and one outbound flight back to his city). Possibly, different jury members might take flights on different days.
Constraints: n up to 1e5, m up to 1e5, days up to 1e6, k up to 1e6. Need efficient solution.
We need to choose for each city i (1..n) an inbound flight (from i to 0) and an outbound flight (from 0 to i) such that: if inbound flight arrives on day d_in, and outbound flight departs on day d_out, then the jury member can work on days from (d_in+1) to (d_out-1) inclusive? Actually statement: "On his arrival day and departure day jury member is not able to discuss the olympiad." So they cannot work on the day they arrive or the day they depart. So the period where they are present and can work is the interval between arrival day and departure day, but not including endpoints. To have them work together for k days, we need that there exists a contiguous block of k days where all jury members are present and can work. This means for each jury member, the arrival day must be ≤ (first day of work block - 1) and departure day ≥ (last day of work block + 1). Alternatively, if the work period is days [L, R] inclusive (R - L + 1 = k), then for each jury member, we require arrival_day < L and departure_day > R? Wait: On arrival day and departure day they can't work. So if they arrive on day A, they cannot work on day A. If they depart on day D, they cannot work on day D. So to be able to work on day x, we need A < x < D. So for all days in [L,R] to be workable, we need for each x in [L,R], A < x < D => A < L and D > R. Actually if A < L and D > R, then for any x in [L,R], we have A < L ≤ x ≤ R < D => A < x and x < D. So that works. However, could A = L-1? Then A < L, yes. D = R+1, then D > R, yes. But if A = L, then cannot work on day L because arrival day, so not allowed. So requirement: arrival_day <= L-1? Actually need A < L. So arrival_day ≤ L-1. Similarly, departure_day ≥ R+1. So we need arrival_day < L and departure_day > R. So arrival_day ≤ L-1 and departure_day ≥ R+1.
But careful: if they arrive on day L-1, they can't work on day L-1, but that's not in the work period if work period is [L,R]. That's okay. So indeed the constraints are: for each city i, choose an inbound flight (arrival at 0) on day A_i, and an outbound flight (departure from 0) on day D_i, such that A_i < L and D_i > R, with L,R satisfying R-L+1 = k. Also, it is allowed for a jury member to stay longer. There is no requirement that they are in Metropolis continuously? Actually they must be there for the entire interval? They could possibly leave and come back? But since they need to be present on all work days, if they leave early they can't work on later days. Typically you'd assume they stay continuously, but flights are one-way; they could take multiple flights? The problem says: "arrange the cheapest way to bring all of the jury members to Metropolis, so that they can work together for k days and then send them back to their home cities." It likely implies each jury member will travel from his home city to Metropolis (once), stay there (maybe with extra days), and then travel back to his home city (once). There is no reason to take extra flights because that would increase cost. So we can assume each jury member takes exactly one inbound and one outbound flight. So we need to choose one inbound and one outbound flight per city.
Additionally, flights are given with days. There might be multiple flights on same day, from different cities or same city? For each city, there could be multiple inbound/outbound flights. We need to pick at most one inbound and one outbound per city.
Goal: minimize total cost sum_i (cost_in_i + cost_out_i) subject to existence of L,R (R-L+1=k) such that for all i: A_i < L and D_i > R.
Alternatively, we can think of selecting a window of k work days. For each city, we need to pick inbound flight arriving before L and outbound flight departing after R. The cost contributions for each city can be considered separately, but they are coupled through the common L,R.
We can precompute for each possible L (or R) the minimal total inbound cost to have all jury members arrive before L, and minimal total outbound cost to have all jury members depart after R. Then answer = min_{L} (inbound_cost_before(L) + outbound_cost_after(L+k-1)). But careful: L must be such that we can find inbound and outbound for each city meeting the constraints. If for some L, inbound_cost_before(L) is infinite (impossible) or outbound_cost_after(L+k-1) is infinite, then that L is not feasible.
Thus we need to compute:
For each day d (or more precisely, for each possible L value), the minimal total cost to bring all jury members to Metropolis arriving on some day ≤ L-1? Actually we need arrival_day < L, i.e., arrival_day ≤ L-1. So we consider L as the first work day. Then the inbound flights must have arrival day ≤ L-1. So we need to compute, for each possible threshold day T (where T = L-1), the minimal total cost to have all jurors arrived by day T (i.e., arrival_day ≤ T). Similarly, for outbound, we need departure_day > R, where R = L+k-1. So departure_day ≥ R+1. So define threshold U = R+1, need departure_day ≥ U. Compute minimal total cost to have all jurors depart on or after day U.
Thus, answer = min over L (1.. something) such that L >=1? Actually days start from 1 (given d >=1). The work days must be within some range; L could be any day from minimal arrival day+1 to max departure day- k? But we can handle by scanning possible L.
We need to compute prefix minima for inbound: For each day T (arrival day threshold), the minimal total cost to have all jurors arrived by that day. Similarly suffix minima for outbound: For each day U, the minimal total cost to have all jurors depart on or after that day.
But careful: The inbound flights must be chosen per city from flights that go from city i to 0 (arrival at 0 on day d). For each city i, among flights with arrival day d (i->0) we can choose the cheapest flight that arrives on or before T. However, if we choose a flight arriving earlier, it might be cheaper. But the requirement is just arrival_day ≤ T, so for a given T, the optimal inbound for city i is the minimum cost among flights from i to 0 with d ≤ T. Because we want to minimize total cost, we can independently pick per city the cheapest flight that satisfies the constraint. There's no interaction between cities. So inbound_total_min[T] = sum_i min_cost_inbound_i(d ≤ T). If for any i there is no such flight, then inbound_total_min[T] = INF (impossible). Similarly, outbound_total_min[U] = sum_i min_cost_outbound_i(d ≥ U) for flights from 0 to i (departure day d). However, note that outbound flights are departing from Metropolis; the day of departure is d. The requirement is departure_day ≥ U (since we need D > R, so D >= U = R+1). So we need flights with departure day d ≥ U. For each city i, we take the cheapest flight from 0 to i with d ≥ U.
Thus the problem reduces to:
Given flights: inbound: for each city i, list of (day, cost) for flights i->0.
Outbound: for each city i, list of (day, cost) for flights 0->i.
Compute for each possible day T (from 1 to max_day maybe up to 1e6+?) the sum over i of min cost among inbound flights with day ≤ T. Similarly for each day U compute sum over i of min cost among outbound flights with day ≥ U.
Then answer = min_{L} ( inbound_total_min[L-1] + outbound_total_min[L+k] )? Actually careful: L is first work day. Then inbound must be ≤ L-1. So threshold for inbound: T = L-1. Outbound must be ≥ R+1 = (L+k-1)+1 = L+k. So we need inbound_total_min[T] and outbound_total_min[U] with U = L+k. But note that L can be as low as 1? If L=1, then inbound must be ≤ 0, but days start from 1; so no inbound flight can have day ≤ 0. So that's impossible unless we define that inbound_total_min[0] = sum of min costs for flights with day ≤ 0 which is impossible. So we need L such that L-1 >= minimum possible day. Similarly, L+k <= max day? Actually outbound must have flights with day ≥ L+k. So we need L such that inbound_total_min[L-1] is finite and outbound_total_min[L+k] is finite.
We can compute inbound_total_min array for all T from 0 up to MAX_DAY (maybe 1e6+? days up to 1e6). But note that days can be up to 1e6. n up to 1e5. So we can have arrays of size up to 1e6+ something, which is okay (1e6 integers ~ 4MB). However we need to compute for each T the sum of minima per city. If we update per city by scanning days, we need efficient method.
Approach: For each city i, we can sort its inbound flights by day. Then we can compute the prefix minimum cost up to each day. But we need to combine across cities to get total sum for each T. Since days are up to 1e6, we could maintain an array best_in[T] that is the sum of best costs per city up to T. But we cannot recompute from scratch for each T.
We can use a sweep line over days. Initialize an array current_min_cost[i] = INF for each city, and current_total = 0 (or INF if some cities missing). We also maintain a flag count of cities for which we have at least one inbound flight? Actually we need to know when a city becomes reachable (i.e., has at least one flight with day ≤ T). For days T from 1 to MAX_DAY, we consider all flights that depart on day T (actually inbound flights arrival day = T) and update the minimum cost for that city if cost < current_min_cost[i]. Then after processing day T, we set inbound_total_min[T] = sum of current_min_cost[i] if all cities have non-INF; else INF. Similarly for outbound we can sweep from right to left.
Thus we need to group flights by day. Since m up to 1e5, and MAX_DAY up to 1e6, we can have array of vectors for each day. That's okay: allocate vector< pair<city, cost> > for each day. However MAX_DAY could be up to 1e6, that's fine. Alternatively, we could use map from day to list, but array is simpler.
But note: The day d can be up to 10^6, so we can create arrays of size max_day+2 (maybe 1e6+10). That's 1e6 entries, each vector overhead maybe heavy but if we store vectors only for days that have flights, we can use map. But with up to 1e5 flights, we could store them in a map from day to list. But also we need to sweep from 1 to max_day (maybe up to 1e6) and for each day we need to update. If we use arrays of vectors, each day without flights has empty vector; that's okay memory wise: vector for each day (1e6 vectors) might be heavy because each vector is a small object (like 24 bytes per vector) leading to 24 MB, plus overhead. That's acceptable? 1e6 * 24 = 24 MB. Actually typical implementation of std::vector is three pointers (or two pointers + allocator) about 24 bytes on 64-bit. 24 million bytes = 24 MB, which is okay within typical memory limit (256 MB or 512 MB). Plus storing flights themselves: each flight as a pair (city, cost) maybe 8 bytes each? Actually city up to 1e5 fits in int, cost up to 1e6 fits in int, so pair<int,int> 8 bytes; m=1e5 => 0.8 MB. So total memory maybe < 50 MB, acceptable. However we need two such arrays: inbound and outbound. So that's double: inbound per day vector and outbound per day vector. That's about 48 MB for vectors plus data. Still okay.
But we also need arrays for inbound_total_min and outbound_total_min of size up to max_day+2 (maybe 1e6+10). Each can be long long (8 bytes) => ~8 MB each. So overall maybe 70 MB, fine.
Alternative: use sorting of flights by day and then sweep with pointer, without per-day vectors. That might be more memory efficient. We can sort all inbound flights by day, then while iterating over days T, we process all flights with day = T and update. That's similar but without storing per-day vectors: we sort flights and then use an index pointer to iterate. That's simpler and memory-friendly. So let's do that: Collect all inbound flights (i->0) as tuples (day, city, cost). Sort by day. Similarly outbound flights (0->i) sorted by day.
Then we sweep over T from 1 to max_day (or maybe min_day to max_day). We maintain current_min_cost[i] and current_total sum. Initially, current_min_cost[i] = INF for all i, current_total = 0 (or INF if any city missing). Actually better: we also maintain count of cities that have at least one flight seen so far. Since we need total sum only when all cities have at least one flight (i.e., current_min_cost[i] != INF). So we can track number of cities covered. When we update a city, if its previous min was INF, we increment covered count and add cost to total; else we subtract previous and add new.
We then set inbound_total_min[T] = (covered == n) ? total : INF.
Similarly for outbound: sweep from max_day down to 1: maintain current_min_cost[i] for flights with day >= current day. We sort outbound flights by day descending, and process.
But careful: For outbound, we need min cost among flights with day >= U. So we can sort outbound flights by day ascending, then sweep from max_day down to 1, adding flights with day == current day? Actually when going from high days to low days, we want to include flights with day >= U. If we sweep U decreasing, then at each step we add flights that have day == U (since those become eligible when U decreases). So we can sort outbound flights by day descending, and as we go from max_day down to 1, we process flights with day == current U, updating min cost for that city. That yields suffix minima.
Thus we can compute two arrays:
prefix_cost[T] for T from 0..max_day (where T = day threshold for inbound: arrival_day ≤ T). We'll compute for T from 1 to max_day. Also we might need T = 0 (no day). Set prefix_cost[0] = INF because no flights.
suffix_cost[U] for U from 1..max_day+1 maybe. We'll compute for U from 1 to max_day. Also need U = max_day+1? Actually if R = max_day, then U = R+1 could be max_day+1, but there are no flights with day >= max_day+1, so suffix_cost[max_day+1] would be INF unless we consider that we don't need flights for days beyond? Actually we need departure_day >= U. If U > max_day, impossible. So we can compute suffix_cost for U up to max_day, and also set suffix_cost[max_day+1] = INF. Similarly, we might need prefix_cost for T up to max_day, and prefix_cost[0]=INF.
But note: days are up to 1e6, but we need to consider T = L-1 and U = L+k. L can be such that L-1 = 0, but that's impossible. However we can compute arrays for indices 0..max_day (maybe plus extra). The sweep will fill for each day. We can then compute answer as min over L such that 1 <= L <= max_day? Actually L must be at least 1, and L+k <= max_day? Because we need U = L+k <= max_day? Actually we need departure_day >= U, and there are flights with days up to max_day. If U > max_day, then there is no flight that satisfies d >= U, so impossible. So we need U <= max_day. So L <= max_day - k. Also L >= 2? Not necessarily; if L=1, inbound must be ≤0 impossible, so L must be at least min_arrival_day+1? But we can just compute with arrays; for L where L-1 < 1, prefix_cost[L-1] is prefix_cost[0] which we set INF. So it will be excluded.
Thus answer = min_{L=1}^{max_day - k} ( prefix_cost[L-1] + suffix_cost[L+k] )? Wait, we need inbound before L: arrival_day ≤ L-1. So we use prefix_cost[L-1]. And outbound after R = L+k-1, so departure_day ≥ L+k. So use suffix_cost[L+k]. But careful: L could be such that L+k may exceed max_day+1? We only consider L up to max_day - k, so L+k ≤ max_day. Then suffix_cost[L+k] is defined. But also we need to consider L such that L+k = max_day+1? That would require L = max_day - k +1, then L+k = max_day+1 > max_day; no flights. So we don't consider.
Thus iterate L from 2? Actually we can start L from 1 to max_day - k (inclusive). Compute prefix_cost[L-1] + suffix_cost[L+k]. Take min. But we need to define prefix_cost array for index 0 to max_day. We'll compute for days from 1 to max_day. So prefix_cost[0] = INF (impossible). Similarly, we'll compute suffix_cost for days 1..max_day. For day > max_day, it's INF. So we can define an array of size max_day+2, with suffix_cost[max_day+1] = INF.
But note: There might be days with no flights; our sweep will still assign values. For prefix: as we go day by day, prefix_cost[T] equals previous total if no update, or updated after processing flights of that day. So we can compute prefix_cost[T] for each T. For outbound, we similarly compute suffix_cost[U] for each U from max_day down to 1.
Time complexity: Sorting flights O(m log m). Sweeping over days up to max_day (which could be up to 1e6) with updates per flight O(m + max_day). That is fine.
Edge Cases: If there are cities with no inbound flights at all, then prefix_cost will never become finite for any T, answer -1. Similarly outbound.
But we must be careful: The inbound flight for a city must be from that city to 0; we can choose any day ≤ T. As we sweep forward, we maintain the minimal cost seen so far for each city. That's correct because if we see a cheaper flight later, we can update, but for a given T, we need the minimum among all flights with day ≤ T. Since we process in increasing day order, we update min as we see flights, and after processing day T, we have the minimal cost among flights with day ≤ T. So prefix_cost[T] is correct.
For outbound, we sweep backward: we maintain minimal cost for each city among flights with day ≥ current U. As we go from high days down, we add flights with day == U to the current set, updating min. So after processing day U, we have the minimal cost for each city among flights with day ≥ U. So suffix_cost[U] is correct.
Now about using long long for total cost as costs up to 1e6 and n up to 1e5, total up to 1e11, fits in 64-bit.
Compute inbound prefix:
Initialize cur_min[1]=INF, cur_min[2]=INF, covered=0, total=0.
Day1: process inbound flight city1 cost5000: cur_min[1] from INF to 5000, covered=1, total=5000 -> prefix[1] = total (since covered=2? no covered=1) -> prefix[1] = INF? Actually we need all cities covered. So prefix[1] = INF (covered<2).
Day2: inbound flight city2 cost6000: cur_min[2] from INF to 6000, covered=2, total=5000+6000=11000 -> prefix[2] =11000.
Day3: inbound flight city2 cost5500: previous cur_min[2]=6000, update to 5500, total becomes 5000+5500=10500, covered=2 -> prefix[3]=10500.
No more inbound. For days >3, prefix[T] remains 10500. So prefix[T] for T>=3 =10500.
Outbound suffix:
Sort flights by day descending:
day15 city2 cost9000
day9 city1 cost7000
day8 city2 cost6500
Sweep from max_day=15 down to 1.
Initialize cur_min[1]=INF, cur_min[2]=INF, covered=0, total=0.
Start at day15: process flight city2 cost9000 -> cur_min[2]=9000, covered=1, total=9000 -> suffix[15] = INF? covered<2 so INF.
Day14: no flights -> same as day15? Actually we need to assign suffix[14] = total if covered==2 else INF. Since no changes, covered still 1, so suffix[14]=INF.
Day13: similar INF.
Day12: INF
Day11: INF
Day10: INF
Day9: process flight city1 cost7000: cur_min[1]=7000, covered=2, total=9000+7000=16000 -> suffix[9]=16000
Day8: process flight city2 cost6500: previous cur_min[2]=9000, update to 6500, total becomes 7000+6500=13500 -> suffix[8]=13500
Day7: no flights -> suffix[7]=13500
...
Day1: suffix[1]=13500? But careful: For days less than 8, still all flights with day>=U are those with day >=U. Since we have processed all flights (days 8,9,15), and min costs are city1:7000 (best outbound for city1 is day9 cost7000; could there be a better flight after day8? Actually there is only day9 for city1. For city2, min among days>=U could be 6500 if U<=8, but if U=7, flights days >=7 includes days 8,9,15; min for city2 is min(6500,9000)=6500. So yes. So suffix[U] for U <=8 = 13500. For U=9, only flights with day >=9: city1 day9 cost7000, city2 day9? none, but city2 day15 cost9000; so min city2=9000, total=16000. So suffix[9]=16000. For U=10..14, flights day >=10: city2 day15 cost9000, city1 none => city1 missing, so INF. Actually careful: for U=10, we need flights with day >=10. We have city2 day15, but city1 none -> missing city1, so suffix[10]=INF. But in our sweep, after processing day9 we had covered=2, but when we go from day9 to day8, we processed day8 flight. But when moving downwards, we should update before computing suffix for that day. The typical backward sweep: we start at max_day+1 where no flights, then go down, and for each day U, we first incorporate flights that depart exactly on day U (since those become eligible when U decreases to that day). So the state after processing day U corresponds to flights with day >= U. So we need to compute suffix[U] after processing flights of day U. So for U=10, we have not processed any flight with day=10, but we have processed days 15,14,13,12,11,10? Actually we go from max_day down to 1. At day 15 we process flight day15, then day14 nothing, day13 nothing, day12 nothing, day11 nothing, day10 nothing. At day10, after processing (none), the state reflects flights with day >=10 (we have processed day15 and also will process days 14-10? Actually we have only processed days >=10 so far: we started at 15, processed 15; then moved to 14, processed flights on 14; ...; by the time we are at day 10, we have processed all flights with days from 15 down to 10, i.e., days >=10. So after processing day 10 (no flight), we have state: city2 from day15 is 9000, city1 none. So covered=1, total=9000. So suffix[10] should be INF. Our earlier statement that suffix[7]=13500 is correct because at day7, we have processed days 15 down to 7, which includes flights days 8,9,15. So covered=2, total=13500. So suffix[7]=13500. So correct.
Now compute answer: k=5. Need L such that prefix[L-1] finite and suffix[L+5] finite. L from 1 to max_day -5 = 15-5=10? max_day=15, so L up to 10? Actually max_day=15, L+k = L+5 <= 15 => L <=10. Also L>=1. But L=1 gives prefix[0] INF. L=2: prefix[1]=INF (since at day1 not all cities covered) => INF. L=3: prefix[2]=11000, suffix[8]=13500 => sum 24500. L=4: prefix[3]=10500, suffix[9]=16000 => sum 26500. L=5: prefix[4]=10500, suffix[10]=INF => INF. L=6: prefix[5]=10500, suffix[11]=INF => INF ... L=10: prefix[9]=10500, suffix[15]=INF? suffix[15]=INF (since at day15 only city2 covered) => INF. So min is 24500, matches sample.
No outbound for city2. So outbound suffix will be missing city2 for all U, so INF everywhere. Answer -1.
Implementation Steps:
Read n,m,k.
Determine max_day from flights (maybe up to 1e6, but we can also dynamically determine max needed: we can compute max day among flights, and then allocate arrays up to that + k + 2, but we need to sweep over days from 1 to max_day. However, days can be up to 1e6, and m up to 1e5. So we can just find max_day among all flights. But we also need to consider L up to max_day - k; if max_day is small, we need to consider up to that. But we also need to compute prefix and suffix for days up to max_day. We might also need prefix for day = L-1, and suffix for day = L+k. If L+k can be up to max_day, it's fine. But L-1 could be 0; we handle that as INF. So we can set max_day = maximum d among all flights. However, if there are flights with days up to 1e6, we need to allocate arrays of that size. But note: days may be up to 1e6, which is fine.
But there is nuance: Some flights might have days beyond max_day we consider? No, max_day is max among flights.
Collect inbound flights: vector<tuple<int,int,int>> or just store as struct. Actually we need for sorting: we need to process in increasing order. So we can store vectors of pairs (day, (city, cost)). But we'll need to sort by day. So create array of vectors: perhaps vector< pair<int, pair<int,int>> > but then sort. Simpler: create struct Flight { int day, city, cost; }. Then sort by day. We'll have inbound list and outbound list.
Compute prefix_total array: we can create a vector pref(max_day+2, INF). But we don't know max_day yet until we read all flights. So we read flights and simultaneously track max_day. After reading, we allocate arrays of size max_day+2 (or maybe size 1e6+10 if we want to avoid scanning for max). But given constraints, max_day could be up to 1e6; but if it's less, we save a bit. But we can just allocate 1e6+10 (since 1e6 is okay). However, note that days can be up to 10^6, but maybe they can be up to 10^6? Yes.
But wait: d can be up to 10^6, but k can be up to 10^6, and L can be up to d_max - k. So we need arrays of size up to d_max + something. If we allocate static arrays of size 1,000,002, that's fine.
But we need to store pref and suff arrays of that size. So let's define MAX_DAY = 1000000 (maybe plus a few). However, note that days could be up to 10^6, but the problem statement says 1 ≤ di ≤ 10^6. So indeed max_day ≤ 10^6. So we can allocate arrays of size 1000005. That's safe.
But careful: We also need to consider L-1 = 0; we can store pref[0] as INF. So array indices 0..MAX_DAY+1 maybe.
Thus we can set MAXD = 1000000 + 5.
But what about the flights with day exactly 10^6? That's okay.
We'll then compute pref: we need to sweep over T from 1 to MAXD? Actually we only need up to max_day. But we might also need pref for days up to max_day. But if we allocate up to MAXD, we can compute for all days up to MAXD; but that would include many days without flights, but that's okay: we would still process those days in O(MAXD) which is 1e6, which is acceptable. However, we also need to sort flights and update when we encounter flights. We can process by iterating day from 1 to max_day (or MAXD). But if we go to MAXD (1e6) every time, that's okay (1e6 operations). But we need to know at which days there are flights to update. We can keep an index pointer into sorted inbound list. At each day d, we advance pointer while inbound[ptr].day == d, and update. So we don't need per-day vectors. So we can do:
For day = max_day down to 1:
while (ptr < outbound.size() && outbound[ptr].day == day) {
update similarly.
ptr++;
}
suff[day] = (covered == n) ? total : INF_LARGE;
But careful: When sorting outbound descending, we need to process flights in decreasing day order. So we can sort outbound by day ascending, and then iterate day from max_day down to 1, but to efficiently get flights with that day, we might need an index from the end. Alternatively, sort outbound ascending and maintain a pointer from the end moving backwards. Or better: sort outbound ascending, and then create an array of vectors per day for outbound. But we wanted to avoid per-day vectors. We can still do: sort outbound ascending, then when iterating day decreasing, we can start with pointer = outbound.size() - 1, and while pointer >=0 && outbound[ptr].day == day, process and decrement pointer. That works.
So for suffix:
Sort outbound by day ascending.
Initialize cur_min = INF per city, covered=0, total=0.
ptr = outbound.size() - 1 (last index).
For day = max_day down to 1:
while (ptr >=0 && outbound[ptr].day == day) {
city = outbound[ptr].city, cost = outbound[ptr].cost;
update...
ptr--;
}
suff[day] = (covered == n) ? total : INF_LARGE;
But careful: The update for suffix: we want the minimum cost among flights with day >= current day. As we go from high days to low, when we encounter a flight at day d, it becomes eligible for all days <= d (since we are moving downward). So updating as we go is correct. However, there is a nuance: If we see a flight for a city with higher cost than existing min, we ignore; if we see a cheaper one, we update. Since we are processing days descending, we are encountering flights in decreasing day order. Suppose a city has flights on days 5 (cost 10) and 10 (cost 5). When we start at day=max_day=10, we process flight day10 cost5, set min=5. Then later at day=5, we process flight day5 cost10, but 10 > 5, so we keep min=5. That's correct for days <=5: the minimum among flights with day >= some day <=5 includes both flights; the minimum is 5 (since flight day10 qualifies). So correct.
But what about the scenario where a cheaper flight occurs earlier (lower day) and a more expensive later? Example: flights day10 cost10, day5 cost5. When we start at day10, we process day10 cost10 -> min=10. Then at day9..6, min remains 10. At day5, we process day5 cost5, which is cheaper, so we update min to 5. For days <=5, suffix min becomes 5. Is that correct? For day U=6, we need min among flights with day >=6. Those are days 10 (cost10) and maybe day5? No, day5 <6, so not included. So for U=6, the min should be 10. Our suffix[6] would be computed when we are at day=6 in the loop. At that point, we have processed flights for days >=6? We processed day10 at day10, then as we go down to day9,8,7,6, we haven't yet processed day5 because day5 <6. So at day=6, cur_min is still 10. So suffix[6] = 10. That's correct. For day=5, after processing day5, cur_min becomes 5, so suffix[5] = 5. So the algorithm works.
So we can compute suffix properly.
Now we have pref[0..max_day] and suff[1..max_day] plus maybe suff[max_day+1]=INF.
We need to compute answer:
long long ans = INF;
for (int L = 1; L + k <= max_day; ++L) {
int T = L - 1; // inbound threshold
int U = L + k; // outbound threshold
if (pref[T] != INF && suff[U] != INF) {
ans = min(ans, pref[T] + suff[U]);
}
}
But careful: L + k <= max_day? Because we need U = L+k and we need suff[U] to be defined. suff[U] is defined for U from 1 to max_day. If U = max_day + 1, we would need suff[max_day+1] which we could set INF. But L + k could equal max_day + 1? That would require L = max_day - k + 1? Actually if L + k = max_day + 1, then L = max_day - k + 1. But we need U <= max_day for existence, because if U = max_day+1, no flights. So we should only consider L such that L + k <= max_day. However, what if there is a flight on day max_day, then U = max_day+1 is not allowed. So loop L from 1 to max_day - k (inclusive). But also ensure L-1 >= 0 (always true). Note that L can be 1, but pref[0] is INF, so fine.
But maybe there is a case where inbound flights can happen on day 0? No, days start from 1.
Edge Cases: if max_day is less than k+1? Actually we need at least two days? Not necessarily; but L must be at least 1, and L+k <= max_day. So if max_day < k+1? Then there is no L satisfying L+k <= max_day (since min L=1 gives 1+k <= max_day => max_day >= k+1). So answer -1 if no L. But also there could be possibilities if inbound threshold = 0? No, because work days require arrival before first work day, and departure after last work day. So need both.
Now we need to ensure we use correct INF values: something like 1e18.
Now consider complexity: Sorting O(m log m). Sweeping over days up to max_day (max 1e6) and each flight processed once, so O(max_day + m). Acceptable.
Memory: cur_min arrays of size n+1 (1e5+1) of long long or int? cost up to 1e6, INF can be large, so long long.
Now we must consider that flights might have duplicate days, multiple flights for same city, etc. The update logic handles.
Potential pitfalls:
The inbound flights: need to be flights from city i to 0. Outbound: from 0 to i.
Input: exactly one of fi, ti is zero. So we can classify.
City numbering: 0 is Metropolis, cities 1..n.
We should also consider that some city might have no inbound or no outbound flights. Then pref/suff will never become all-covered, answer -1.
The day range: d up to 1e6, but we can allocate arrays up to 1e6+2.
But we need to determine max_day. Since we are going to loop over days from 1 to max_day, we need to know max_day. We can compute as max over all flight days. But what if there are flights with days > max_day? No, we set max_day = maximum d among all flights. However, we also need to consider L up to max_day - k. If max_day is less than k+1, answer -1.
But we also need to compute suffix for days up to max_day. However, what about days beyond max_day? Not needed because U <= max_day.
But note: while computing suffix, we go from max_day down to 1. That's fine.
Now, what about the possibility that we need inbound threshold T = 0? That only occurs if L=1, but then pref[0] is INF. So L=1 cannot be feasible unless there is some way to have arrival_day < 1, impossible. So we can safely start L from 2? But could L be 1 if there is a flight on day 0? No. So we can start L from 2. But we can just start from 1, it's fine.
Edge Cases:
If there are flights on day 1 inbound, and we want L=2, then T=1, that is okay. So we need pref[1] to be computed.
If there are flights on day 1 outbound, and we want L=1? Not allowed.
If k is large but max_day is small, answer -1.
Now we need to check: The work period of k days: they need to be consecutive days. It doesn't matter which days; we can choose any L.
One nuance: The jury members must be present for k days, but they can also arrive earlier and depart later. The constraint that on arrival and departure days they cannot work means the work days must be strictly between arrival and departure days. So our formulation is correct.
Now let's test with some custom scenarios.
Case: n=1, one inbound flight day 5 cost 10, one outbound flight day 6 cost 20, k=1. Then need L such that arrival < L and departure > L (since R = L, because k=1 => R=L). So need A < L < D. So L must be between A+1 and D-1. Here A=5, D=6, so L must be 6? Wait A=5, D=6. A < L and D > L. So L must satisfy 5 < L < 6 => no integer L. So impossible. Our formulation: L is first work day, R = L + k -1 = L. So we need A ≤ L-1 and D ≥ L+1. With A=5, D=6: For L=6, we need A ≤5 (5 ≤5 true) and D ≥7 (6≥7 false). For L=5: A ≤4 false. So no L. So answer -1. That matches.
Case: inbound day 5 cost 10, outbound day 7 cost 20, k=1. Then possible L=6? A ≤5 true, D ≥7 true. So answer 30. Our loop: max_day=7, k=1 => L from 1 to 6? Actually L up to max_day - k =6. Check L=6: T=5, pref[5] must be finite: for city1, min cost with day ≤5 is 10 (since flight day5). So pref[5]=10. U = L+k =7, suff[7] = min cost outbound with day ≥7: flight day7 cost20 => 20. Sum=30. Good.
Case: multiple cities, with different days.
Now, we need to ensure we treat INF correctly.
Potential issues: The array sizes for pref and suff should be up to max_day+2 to safely index L+k when L+k = max_day. That's fine. We'll allocate size max_day+3 perhaps.
Also note: We must be careful with indexing: In the loop, we need to access suff[U] where U = L + k. Since L can be up to max_day - k, U up to max_day. That's within suff range (1..max_day). Also we need to access pref[T] where T = L-1, which can be 0..max_day-1. We'll have pref[0] set INF. So we need pref array size at least max_day+1? Actually we need up to max_day because T could be max_day-1, but pref[max_day] also computed, though we might not need it for T = max_day? Actually T max = L-1 where L = max_day - k, so T max = max_day - k - 1, which is < max_day. But we might still compute pref up to max_day for completeness.
Now, consider the scenario where there is an inbound flight on day max_day and outbound flight also on max_day. Then maybe L could be such that T = max_day? Not needed as argued.
Implementation details:
We'll read all flights, separate into inbound and outbound vectors.
For inbound: store as (day, city, cost). For outbound: store as (day, city, cost).
Determine max_day = max over all flights' day.
If max_day < k + 1? Actually not strictly needed, but we can check quickly if max_day <= k? Then answer -1 because we need at least one day between? Actually we need L such that L >= 1, L+k <= max_day. So if max_day < k+1, then L can be at most max_day - k which is negative, so impossible. So answer -1.
But also we need inbound and outbound sets to cover all cities. Could be still impossible even if max_day large.
Initialize cur_min array for cities: vector minCost(n+1, INF). We'll also need to know if we have seen a flight for each city? We'll treat INF as not yet.
covered = 0; total = 0.
ptr = 0; size_in = inbound.size().
For day = 1 to max_day:
while (ptr < size_in && inbound[ptr].day == day) {
update
ptr++
}
pref[day] = (covered == n) ? total : INF;
After loop, we also might need pref[0] = INF.
For suffix:
sort outbound ascending.
vector suff(max_day+3, INF); // we will compute for days 1..max_day
vector minCostOut(n+1, INF); // reset
covered = 0; total = 0;
ptr = outbound.size() - 1;
for (int day = max_day; day >= 1; day--) {
while (ptr >= 0 && outbound[ptr].day == day) {
update
ptr--;
}
suff[day] = (covered == n) ? total : INF;
}
// we can also set suff[max_day+1] = INF (implicitly).
Then compute answer:
long long ans = INF;
for (int L = 1; L + k <= max_day; ++L) {
long long incost = pref[L-1];
long long outcost = suff[L+k];
if (incost < INF && outcost < INF) {
if (incost + outcost < ans) ans = incost + outcost;
}
}
if (ans >= INF) ans = -1;
But wait: is L allowed to be such that L-1 = 0 and we have pref[0] = INF. That's fine.
Now need to check sample 1: max_day=15, k=5 -> L from 1 to 10. L=3 gave incost=pref[2]=11000? Actually pref[2]=11000, outcost=suff[8]=13500 sum 24500. Good.
Now check sample 2: inbound: city2 day1 cost5000; city1 day2 cost4500 and 3000. So pref[T] becomes finite from T>=2: pref[2] = 5000+min(4500,3000)=8000. But outbound: only city1 day8 cost6000, no city2. So suff[U] never reaches covered=2, so all INF. So answer -1.
Now test scenario: if there is both inbound and outbound for all cities, but maybe the combination L leads to constraints that are too tight? Our method checks all L.
Now consider scenario where there are flights for a city that are both inbound and outbound, but maybe the cheapest inbound is after some day, but we need it to be before L. If we pick L too early, pref[L-1] might be INF because some city has no inbound before that. So we only consider L where pref[L-1] is finite. Similarly for outbound.
Thus algorithm seems correct.
Now need to ensure we treat day range properly: flights days are up to 1e6. But we also need to consider that L can be up to max_day - k. max_day could be 1e6, k up to 1e6, so L range up to 0 maybe. That's fine.
Now, what about scenario where max_day is 10^6 and k=10^6, then L must satisfy L+10^6 <= 10^6 => L <= 0. So no valid L, answer -1. So we can early return if max_day < k+1.
Now, complexity: O(max_day + m log m). Since max_day up to 1e6, that's okay.
Now, we must also consider that there might be duplicate entries for same city and day with different costs; we handle by min update.
Now, careful about data types: day up to 1e6, but we might need to allocate arrays of that size. That's fine.
But we need to be careful: If max_day is 1e6, then our loops from 1 to 1e6 are fine. However, we also need to sort inbound/outbound vectors of size m (1e5), that's fine.
Now, we need to handle the case where there are no flights at all (m=0). Then n>=1, impossible, answer -1.
Now, one nuance: The flights are either inbound or outbound. But there might be flights for a city i both inbound and outbound, but we treat separately.
Now, possible pitfalls: The cur_min arrays for prefix and suffix use INF initialization. For prefix, when we update, if cur_min[city] is INF, we set it to cost, increase covered and add to total. But what if we encounter a flight with cost INF? Not possible.
Now, after computing pref and suff, we need to compute ans. But what about the possibility that L could be such that L-1 > max_day? Not needed.
Now, we should test with some edge case: n=1, m=2, k=10^6, but days are small. Should return -1.
Now, test with n=1, inbound day 1 cost 5, outbound day 100 cost 10, k=50. Then max_day=100. Compute pref: from day1 onward pref[1]=5. suff: from day100 downward, suff[100]=10. Now L from 1 to 100-50=50. Check L=2: pref[1]=5, suff[52]? suff[52] is cost for outbound with day >=52: only flight day100 =>10, sum=15. L=50: pref[49]=5, suff[100]=10 sum=15. So ans=15. But is it feasible? Need A < L and D > L+49. With inbound day1, A=1, so need 1 < L => L>1, so L>=2. Outbound day100, need 100 > L+49 => L < 51. So L from 2 to 50 works. So ans=5+10=15, correct.
Now, what about scenario where there are multiple inbound flights for a city, and we might choose a later inbound flight because it's cheaper, but that would mean arrival day later, which might affect feasible L. However, our pref[T] uses the minimum cost for each city among flights ≤ T. So for a given T, we choose the cheapest flight that arrives by T, even if it's later. That's okay, because any flight with day ≤ T is allowed. If we pick a flight arriving later but still ≤ T, that's allowed and cost minimal. So pref[T] is optimal for that T.
Similarly for suffix.
Thus the approach should produce minimal total cost.
Now confirm with more complex: Suppose for a city, there is an inbound flight day5 cost100, day10 cost10. For T=10, pref[10] would choose cost10. But for T=9, pref[9] would be cost100 (since day10 not allowed). So if we need L such that T=9, we must pay 100; if L such that T=10, we can pay 10. So our optimization across L will pick best combination.
Now we need to be careful about the day range: The work days must be consecutive k days. Our L variable represents first work day. The conditions are:
For each city, inbound day < L.
For each city, outbound day > L+k-1.
Yes.
Now check: Is it allowed that a jury member arrives after the work period starts? No, must be before start. So inbound day must be < L. So our condition is strict: arrival day less than L. So arrival day ≤ L-1. So our T = L-1. Good.
Outbound day must be > R = L+k-1, so outbound day ≥ R+1 = L+k. So U = L+k. Good.
Now we must also consider the possibility that some jury member could take an inbound flight that arrives on the same day as another's outbound flight? Not relevant.
Now, the algorithm seems correct.
Now, we also need to ensure that we don't overflow with INF. Use something like 1e18.
Now, implement.
Potential improvements:
Since we need to compute pref and suff for days up to max_day, we can reduce the loop to only days up to max_day. But we also need to compute pref[L-1] for L from 1 to max_day - k. So we need pref for indices up to max_day - k - 1. That's less than max_day. So we could compute pref up to max_day and suff up to max_day.
Implementation steps:
Read n,m,k.
Define vectors inbound, outbound.
max_day = 0.
For each flight: read d, f, t, c.
if t == 0: inbound.emplace_back(d, f, c) // f is city >0
else: outbound.emplace_back(d, t, c) // t is city >0
max_day = max(max_day, d)
If (max_day < k+1) { output -1; return; } // optional early check
Sort inbound by day ascending.
Compute pref array: vector pref(max_day+2, INF);
// We'll compute pref[0] separately: pref[0] = INF.
// We'll compute for day 1..max_day.
vector minIn(n+1, INF);
int coveredIn = 0;
long long totalIn = 0;
int idx = 0;
int inSize = inbound.size();
for (int day = 1; day <= max_day; ++day) {
while (idx < inSize && inbound[idx].day == day) {
int city = inbound[idx].city;
long long cost = inbound[idx].cost;
if (cost < minIn[city]) {
if (minIn[city] == INF) {
coveredIn++;
totalIn += cost;
} else {
totalIn += cost - minIn[city];
}
minIn[city] = cost;
}
idx++;
}
if (coveredIn == n) pref[day] = totalIn;
else pref[day] = INF; // but we can assign as INF anyway.
}
// pref[0] remains INF.
Compute suff array: vector suff(max_day+3, INF);
Sort outbound ascending by day.
vector minOut(n+1, INF);
int coveredOut = 0;
long long totalOut = 0;
int outSize = outbound.size();
int idxOut = outSize - 1;
for (int day = max_day; day >= 1; --day) {
while (idxOut >= 0 && outbound[idxOut].day == day) {
int city = outbound[idxOut].city;
long long cost = outbound[idxOut].cost;
if (cost < minOut[city]) {
if (minOut[city] == INF) {
coveredOut++;
totalOut += cost;
} else {
totalOut += cost - minOut[city];
}
minOut[city] = cost;
}
idxOut--;
}
if (coveredOut == n) suff[day] = totalOut;
else suff[day] = INF;
}
// suff[max_day+1] is INF by default.
Compute answer:
long long ans = INF;
for (int L = 1; L + k <= max_day; ++L) {
if (pref[L-1] != INF && suff[L+k] != INF) {
long long sum = pref[L-1] + suff[L+k];
if (sum < ans) ans = sum;
}
}
if (ans >= INF) ans = -1;
Output ans.
Now, we must consider that some cities may have no inbound flights at all: then coveredIn never reaches n, pref all INF. So ans stays INF. Output -1. Good.
Similarly outbound.
Now, test with sample 1:
max_day=15. pref[2]=11000, pref[3]=10500, etc. suff[8]=13500, etc. ans=24500.
Now, we should also test scenario where L could be very large, but we only go up to max_day - k. That's fine.
Now, consider scenario where k=0? According to constraints k ≥ 1, so not needed.
Now, check scenario where there are multiple inbound flights for a city, and we update minIn. Our update logic: if cost < minIn[city], we adjust total. This works because we only care about minimum cost seen so far. However, we must ensure that if we see a flight with a higher cost later (or same day but higher cost), we ignore. That's fine.
But what about flights that appear out of order? We sort by day, so we see them in increasing day. For inbound, we only care about flights with day ≤ current day. Since we process in increasing day, we are updating min cost as we see new flights. But note: Suppose we see a cheap flight later (higher day) that we want to use for earlier days? No, because for earlier days (small T), that flight wouldn't be available as its day > T. So our algorithm for pref[day] after processing day uses only flights with day ≤ day. If a cheaper flight occurs later, it won't affect pref for earlier days. That's correct.
Now, consider the update for suffix: we process descending days, and we update minOut as we see flights with that day. This gives the min among flights with day ≥ current day. Since we are moving from high days down, we are effectively adding flights as we go to lower days. That's correct.
Now, ensure that we reset minOut for suffix, we need separate array from minIn.
Now, potential performance: loops over days up to 1e6, and while loops for each flight. Good.
But what if max_day is huge? d up to 1e6, that's okay.
Now, memory: pref and suff arrays each of size 1e6+5 ~ 8 MB each (if using long long). cur_min arrays each of size n+1 ~ 800KB each (if using long long, 8 * 1e5 = 0.8 MB). So total memory < 20 MB, fine.
But there is one nuance: The problem states n up to 1e5, m up to 1e5, k up to 1e6. So we are good.
Now, we should test additional cases.
Case: n=3, inbound: city1 day1 cost1; city2 day2 cost2; city3 day3 cost3. Outbound: city1 day10 cost1; city2 day11 cost2; city3 day12 cost3; k=5. Then max_day=12. Compute pref: from day3 onward, total = 1+2+3=6. suff: from day10? Actually for suffix: at day12, only city3 -> not all; day11, city2+? Actually let's compute: outbound sorted: (10,1,1),(11,2,2),(12,3,3). Processing descending:
day12: process city3 cost3 => covered=1 total=3; suff[12]=INF.
day11: process city2 cost2 => covered=2 total=5; suff[11]=INF.
day10: process city1 cost1 => covered=3 total=6; suff[10]=6.
day9: no processing, covered=3 total=6 => suff[9]=6.
...
day1: suff[1]=6.
Now L from 1 to 12-5=7. Need pref[L-1] and suff[L+5]. For L=2: pref[1] (day1 not all covered) = INF -> skip. L=3: pref[2] INF. L=4: pref[3]=6, suff[9]=6 sum=12. L=5: pref[4]=6, suff[10]=6 sum=12. L=6: pref[5]=6, suff[11]=INF -> skip. L=7: pref[6]=6, suff[12]=INF skip. So ans=12. Is that feasible? For L=4: work days 4..8 (since k=5 => 4,5,6,7,8). Need inbound <4: city1 day1 OK, city2 day2 OK, city3 day3 OK. Outbound >8: need day >8 => city1 day10, city2 day11, city3 day12: all >8, OK. So cost 1+2+3+1+2+3=12. Good.
Now what if inbound cheap flight appears later but outbound cheap appears earlier; algorithm should pick optimal L.
Now consider scenario where we have multiple options for each city. Should be fine.
Now consider scenario where we need to handle large values, use 64-bit.
Now consider scenario where there are flights on same day for same city with different costs; we pick cheapest.
Now consider scenario where we have flights with day = L-1 or L+k; we need to be careful: inbound day = L-1 is allowed (since arrival day < L, so L-1 works). So pref[L-1] includes flights on day L-1. Similarly outbound day = L+k is allowed? Since departure day > R, with R = L+k-1, so departure day >= L+k is allowed. So outbound on day L+k is allowed. So suff[L+k] includes flights on exactly day L+k. That's correct.
Now, check that our suffix computation includes flights on day U when we compute suff[U] after processing flights of day U? In the descending loop, at day = U, we process flights with day == U, then set suff[U]. That includes those flights. So correct.
Now, we need to ensure that our loop for L runs for L such that L+k <= max_day. For L = max_day - k, then U = max_day, suff[max_day] is defined and includes flights on that day if any. Good.
Now, what about L= max_day - k + 1? That would give U = max_day+1, which we don't have suff, so not considered. So fine.
Now, edge case: max_day might be less than 1? Not possible.
Now, we should also consider that there might be flights with day > max_day? We set max_day to max of all, so fine.
Now, potential performance issue: the for day loop up to max_day (1e6) is fine, but we also have to compute pref and suff for each day, which is O(max_day). Good.
Now, what about memory for pref and suff: we could use vector with size max_day+2. But if max_day=0 (if m=0), then our early check will cause output -1 before allocating arrays. So handle m=0 separately: if m==0 then answer -1 (since n>=1). Or if max_day=0? Actually flights have d≥1, so max_day≥1 if m>0. So fine.
Now, implement.
But careful: When we compute pref[day], we set it to total if covered==n else INF. However, we also need to know that pref[day] for days beyond the last inbound day might still be finite (since we have all cities covered). That's fine.
Now, what about the scenario where there are inbound flights for all cities, but some outbound flights are missing? Then suff all INF, ans -1. Good.
Now, check sample 1 again: It matches.
Now, let's test with a custom case where both inbound and outbound are feasible but the optimal L is at the boundaries.
Case: n=2, inbound: city1 day1 cost10, day100 cost1; city2 day1 cost10, day100 cost1. So pref[0] INF, pref[1]=20, pref[2..99]=20, pref[100]=2 (since cheaper flights). outbound: city1 day200 cost10, day300 cost1; city2 day200 cost10, day300 cost1. So suff[200] =20, suff[199]? Actually compute: outbound flights day300 and day200. Suffix: from max_day=300 down: day300: process city1 cost1? Actually both cities have flights day300 cost1? Actually if both have cost1 day300, then at day300 after processing both, covered=2, total=2? Wait we have two flights: day300 city1 cost1, day300 city2 cost1. But they might appear as separate entries. So after processing day300, minOut for each =1, total=2. Then as we go down to day200, we process day200 flights cost10 each, but they are more expensive, so no update. So suff[200] also 2. Actually check: at day200, we have processed flights with day >=200, which includes day200 and day300. For each city, min is min(10,1)=1, so total=2. So suff[200] =2. For days >300? Not needed. For days <200, say day199, we have processed flights day200 and 300, so total=2. So suff[U] =2 for U <=300? Actually for U <=200, it's 2; for U=201..300, only day300 qualifies? Actually for U=250, flights with day>=250 include day300 only, so we need to check: at day250 in our descending loop, we haven't processed day200 yet (since we go from 300 down to 1). At day250, we have processed days 300..251? Actually when we reach day=250, we have already processed flights with day >=250? We started at day=300, processed day300 flights, then day299 none, ... down to day=251 none, then day=250 we process flights with day ==250 (none). But we still have the state from higher days: we have processed day300 flights, but not day200. So at day=250, minOut for city1 = 1 (from day300), city2 =1, total=2. However, are these flights valid for U=250? Yes, because they have day >=250. So suff[250]=2. That's fine. But what about U=301? not needed.
So outbound total cost minimal is 2.
Now k=50. We need L such that L+k <= max_day=300 => L <=250. Compute ans: we want to minimize pref[L-1] + suff[L+50]. pref is 20 for L-1 < 100, and 2 for L-1 >=100. So if we choose L such that L-1 >=100 (i.e., L>=101), then pref = 2; else pref =20. For outbound, suff[L+50] = 2 for all L+50 <=300 (since L<=250 => L+50 <=300, and suff is 2 for all U ≤300). So best ans = 2+2=4 for L>=101. For L=101, check constraints: inbound cheap flights day100? Actually inbound cheap flights day100 (cost1). Wait inbound cheap flights day100, but need arrival < L => day ≤100? L=101 => arrival <101 => day≤100. So the cheap inbound on day100 qualifies. So yes. So ans=4.
Our algorithm would compute that.
Now, what about if there is a scenario where for some L, pref[L-1] is finite but later we might get a better pref because of cheaper flights later, but that would require L larger, but then suff[L+k] might become larger if cheaper outbound flights are earlier? So the algorithm scanning all L finds minimum.
Now, check scenario where both inbound and outbound have cheap flights only in a middle window, and we need to pick L accordingly.
Now, the only potential issue: The flight days are up to 1e6, but k can be up to 1e6, and max_day may be 1e6. The loop for L goes up to max_day - k, which could be up to 1e6 (if k=1) or down to 0. In worst-case, if k=1, then L from 1 to 999,999? Actually max_day = 1e6, k=1 => L from 1 to 999,999? That's about 1e6 iterations, which is fine. If k is small, it's okay. If k is large, less iterations.
Now, we need to be careful about the condition L + k <= max_day. We must use <= because U = L+k must be ≤ max_day to have suff[U] defined. However, what if L+k = max_day + 1? Not allowed.
Now, note that suff[U] is defined for U up to max_day. If U = max_day+1, we would need to know if it's possible to have departure day >= max_day+1: impossible because no flights beyond max_day. So we exclude.
Thus loop condition is correct.
Now, what about the case where we can have L such that L = 0? Not allowed.
Now, implement in code.
But there is one nuance: Our pref[day] computed for day from 1 to max_day. But what about pref[L-1] where L-1 might be > max_day? That cannot happen because L <= max_day - k, so L-1 <= max_day - k - 1 < max_day, so within range.
Similarly, suff[L+k] where L+k could be max_day, within range.
Now, if max_day is very small (like 0), we would have early exit.
Now, we need to ensure that we set INF to a value larger than possible total cost. Max total cost: each flight cost up to 1e6, at most 2*n flights used (but we sum costs, each city one inbound and one outbound, so max total = 2 * n * 1e6 = 2e11, which fits in 64-bit. So we can set INF = 5e18 (or LLONG_MAX/2). Use 1e18.
Now, consider the possibility of overflow when adding? We'll use long long.
pref[0]=INF.
day1: process (1,1,5000): minIn[1]=5000, covered=1, total=5000 -> pref[1]=INF.
day2: process (2,2,6000): minIn[2]=6000, covered=2, total=5000+6000=11000 -> pref[2]=11000.
day3: process (3,2,5500): update minIn[2] from 6000 to 5500, total=5000+5500=10500 -> pref[3]=10500.
day4..15: no changes, pref[4..15]=10500.
suff:
Initialize idxOut = 2 (since outbound size 3). day=15: while idxOut>=0 && outbound[idxOut].day==15: process (15,2,9000): minOut[2]=9000, covered=1, total=9000 -> suff[15]=INF.
day=14: no flight -> suff[14]=INF.
day=13: ... -> INF.
day=12: INF.
day=11: INF.
day=10: INF.
day=9: while idxOut>=0 && outbound[2]? Actually after processing day15, idxOut becomes 1 (since we decrement). Now day9: check outbound[1].day==9? outbound[1] = (9,1,7000), yes, process: city1 cost7000 -> minOut[1]=7000, covered=2, total=9000+7000=16000 -> suff[9]=16000. idxOut becomes 0.
day=8: while idxOut>=0 && outbound[0].day==8: process (8,2,6500): city2 update: previous minOut[2]=9000, new cost 6500 < 9000, so total becomes 16000 - 9000 + 6500 = 12500? Wait recalc: total before = 16000 (city2 9000, city1 7000). Update city2 from 9000 to 6500: total = 16000 - 9000 + 6500 = 12500. Actually we need to adjust: totalOut = totalOut - old + new. So after update, total=12500. minOut[2]=6500. covered stays 2. Then suff[8]=12500. idxOut becomes -1.
day=7..1: no flights, suff[7..1]=12500.
Thus suff[8]=12500? But we previously thought 13500. Let's recalc manually: In sample, outbound flights: for city2, there are two: day8 cost6500, day15 cost9000. The minimum cost for city2 among flights with day >= some U: For U <=8, min is 6500; for U=9..15, min is 9000. For city1, only day9 cost7000. So for U=8, total = city1 (7000) + city2 (6500) = 13500. But our suffix computed 12500, which is lower. Wait we got city1 7000, city2 6500 => 13500. But our total became 12500. That indicates we mis-updated: When we processed day9, we had city2 9000, city1 7000 total 16000. Then day8, we processed city2 6500, which replaced 9000, so total becomes 16000 - 9000 + 6500 = 12500. That's 7000 + 6500 = 13500? Actually 7000+6500=13500, not 12500. There's a discrepancy: Because when we processed day9, we had city2 9000, city1 7000 total 16000. But city1 7000 is correct. Then day8, we update city2 to 6500, subtract 9000, add 6500 => total = 16000 - 9000 + 6500 = 12500. But 12500 = 7000 + 5500? That's 12500? Wait 7000+6500 = 13500. So why 16000 - 9000 + 6500 = 12500? 16000 - 9000 = 7000, plus 6500 = 13500. I miscalculated: 16000 - 9000 = 7000, then +6500 = 13500. Indeed 7000 + 6500 = 13500. So total = 13500. My mental arithmetic was wrong: 16000-9000=7000, 7000+6500=13500. So it's correct. So suff[8]=13500. Good.
Now ans: L=3 => pref[2]=11000, suff[8]=13500 => 24500. Good.
Now check L=4: pref[3]=10500, suff[9]=16000 => 26500.
inbound: (1,2,5000), (2,1,4500), (2,1,3000) -> sorted: (1,2,5000), (2,1,4500), (2,1,3000) but careful: we should process both on day2. Our update will consider the cheaper 3000 when processing day2 (order: we may process 4500 then 3000, but whichever order, min becomes 3000). So pref: day1: only city2 -> covered=1, total=5000 -> INF; day2: process both city1 flights: first maybe 4500, set minIn[1]=4500, covered=2, total=5000+4500=9500; then process 3000, since 3000 < 4500, update: total = 9500 - 4500 + 3000 = 8000. So pref[2]=8000. For days >=2, pref=8000.
outbound: only (8,1,6000) -> sorted: (8,1,6000). max_day=8? Actually also inbound days up to 2, outbound day8, so max_day=8. Compute suffix:
Start day8: process city1 cost6000 -> covered=1, total=6000 -> suff[8]=INF (since covered=1 <2). day7..1: no changes -> all INF. So suff all INF. So ans stays INF -> -1. Good.
Now, we should test a case where there are flights on day 0? Not allowed.
Now, we need to handle the possibility that some city has both inbound and outbound flights but maybe the cheapest inbound is after cheapest outbound? No coupling.
Now, potential pitfalls:
The inbound and outbound arrays may be empty for some city, causing covered never reaching n.
The loops over days from 1 to max_day: if max_day is large (1e6) but there are few flights, the while loops will rarely trigger. That's fine.
For suffix, when we process days descending, we need to ensure we correctly handle multiple flights on same day. Our while loop processes all flights with that day. Since we sorted ascending, when we iterate descending, we need to start idxOut = outbound.size() - 1 and decrement while matching day. That works as long as the same day flights are contiguous in the sorted list. Since we sort by day ascending, all flights with same day are grouped together, but not necessarily contiguous? Actually they are contiguous because sorting by day groups them. Yes.
For inbound, similarly.
Now, we need to be careful about using long long for cost and total. Use long long.
Now, code now.
But we need to consider the possibility that the answer may exceed 32-bit, so use long long.
Now, one more nuance: The work days are k days. The jury members can stay for more than k days, and they can also arrive earlier and depart later. That's already considered.
Now, are there any scenarios where it's beneficial to have a jury member take an inbound flight that arrives later than L? No, because then they wouldn't be present on first work day. So must be earlier.
Now, the algorithm seems good.
But wait: The condition "On his arrival day and departure day jury member is not able to discuss the olympiad." So if a jury member arrives on day A, he can't work on day A. If he departs on day D, he can't work on day D. But can he work on days between A and D, even if there is a gap? He stays in Metropolis. So yes.
Now, what about the possibility that a jury member could take an inbound flight that arrives after the work period ends? No, that wouldn't allow him to work.
Thus conditions are correct.
Now, think about scenario where we could choose L such that some city's inbound flight arrives exactly on day L-1, and outbound on day L+k. That's allowed.
Now, let's test with some random small cases via brute force to verify correctness. But since we are not coding that here, we can reason.
Potential issue: The problem statement: "All flights in Metropolia depart and arrive at the same day." So flights are same-day. No overnight flights. That's consistent with our model.
Now, check constraints: n up to 1e5, m up to 1e5. The per-city arrays of size n+1 are fine. But we need to ensure we reset them properly between prefix and suffix computations. We'll just create new vectors each time.
Now, note: When computing suffix, we use minOut array. We need to ensure that we use correct data type.
Now, consider if there are multiple flights for same city on same day with different costs. Our update picks the cheapest because we compare cost < minOut[city]. If there are two with same cost, no issue.
Now, implement:
Pseudo-code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
struct Flight {
int day, city, cost;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
int n, m, k;
cin >> n >> m >> k;
vector<Flight> inbound, outbound;
int max_day = 0;
for (int i=0; i<m; ++i) {
int d, f, t, c;
cin >> d >> f >> t >> c;
max_day = max(max_day, d);
if (t == 0) { // f -> 0
inbound.push_back({d, f, c});
} else { // 0 -> t
outbound.push_back({d, t, c});
}
}
// early impossible: if we cannot have both inbound and outbound for all cities, but we will detect.
// Also need at least k+1 days? Actually need L such that L+k <= max_day, and L-1 >= 1? not necessarily.
// We'll just compute.
// sort inbound by day
sort(inbound.begin(), inbound.end(), [](const Flight& a, const Flight& b) {
return a.day < b.day;
});
// prefix
vector<ll> pref(max_day + 2, INF); // index from 0 to max_day
pref[0] = INF; // impossible
vector<ll> minIn(n+1, INF);
int coveredIn = 0;
ll totalIn = 0;
int idx = 0;
int in_sz = inbound.size();
for (int day = 1; day <= max_day; ++day) {
while (idx < in_sz && inbound[idx].day == day) {
int city = inbound[idx].city;
ll cost = inbound[idx].cost;
if (cost < minIn[city]) {
if (minIn[city] == INF) {
coveredIn++;
totalIn += cost;
} else {
totalIn += cost - minIn[city];
}
minIn[city] = cost;
}
idx++;
}
if (coveredIn == n) {
pref[day] = totalIn;
} else {
pref[day] = INF;
}
}
// suffix
sort(outbound.begin(), outbound.end(), [](const Flight& a, const Flight& b) {
return a.day < b.day;
});
vector<ll> suff(max_day + 3, INF);
vector<ll> minOut(n+1, INF);
int coveredOut = 0;
ll totalOut = 0;
int out_sz = outbound.size();
int idxOut = out_sz - 1;
for (int day = max_day; day >= 1; --day) {
while (idxOut >= 0 && outbound[idxOut].day == day) {
int city = outbound[idxOut].city;
ll cost = outbound[idxOut].cost;
if (cost < minOut[city]) {
if (minOut[city] == INF) {
coveredOut++;
totalOut += cost;
} else {
totalOut += cost - minOut[city];
}
minOut[city] = cost;
}
idxOut--;
}
if (coveredOut == n) {
suff[day] = totalOut;
} else {
suff[day] = INF;
}
}
// compute answer
ll ans = INF;
for (int L = 1; L + k <= max_day; ++L) {
ll incost = pref[L-1];
ll outcost = suff[L+k];
if (incost != INF && outcost != INF) {
ans = min(ans, incost + outcost);
}
}
if (ans >= INF) {
cout << -1 << endl;
} else {
cout << ans << endl;
}
return 0;
}
Now, let's double-check boundary conditions: L from 1 to max_day - k inclusive. When L=1, L-1=0, pref[0] is INF, so skip. That's fine.
What about L = max_day - k? Then U = max_day, suff[max_day] is defined. Good.
What about scenario where L-1 may be 0 but there is a hypothetical flight day 0? Not possible.
Now, consider if max_day is 10^6 and we allocate vectors of that size. In C++, vector pref(max_day+2) will allocate that many elements. That's about 8 million bytes (8 MB) for each vector, which is fine. But note: if max_day is 1e6, max_day+2 ~ 1,000,002, times 8 = 8 MB. So pref and suff together 16 MB. plus inbound/outbound lists and min arrays, still under 64 MB.
But we also have vector for inbound and outbound: each Flight contains three ints (day, city, cost). That's 12 bytes (assuming int is 4). Plus overhead? Actually struct with three ints may be 12 bytes if packed. So m=1e5 -> 1.2 MB each, total < 3 MB.
So memory fine.
Now, need to watch out: We used INF = 1e18. But if we add two INF's, could overflow? We only add when both are not INF, else skip. So safe.
Now, confirm with another test: n=1, inbound day1 cost5, outbound day100 cost10, k=50. max_day=100. pref[0]=INF, pref[1]=5 (since coveredIn=1), pref[2..100]=5. suff: sort outbound: (100,1,10). Compute suffix: day100 process -> coveredOut=1 total=10 -> suff[100]=10; day99..1: after day100, idxOut becomes -1, then for day99, coveredOut=1, but not equal to n? n=1, so coveredOut==1 => suff[99]=10? Actually we need to check: In suffix loop, after processing day100, coveredOut=1, totalOut=10. Then for day99, while loop none, coveredOut still 1, which equals n (since n=1), so suff[99] = totalOut = 10. Similarly for all days down to 1, suff[day]=10. So suff[1..100]=10. Then L from 1 to 100-50=50. For L=2, incost=pref[1]=5, outcost=suff[52]=10, sum=15. For L=50, incost=pref[49]=5, outcost=suff[100]=10 sum=15. So ans=15. But is L=2 valid? Need arrival <2 => day1 ok; departure > 2+49=51? Actually R = L+49 = 50? Wait k=50: work days L..L+49 inclusive (50 days). So need departure > L+49. For L=2, need departure > 51, but outbound day100 > 51, ok. So yes. So ans 15. Good.
Now, consider L=1: incost pref[0]=INF skip. So correct.
Now, consider if there is also an outbound flight day 60 cost 1, which is cheaper. Then suffix[U] would be 1 for U <=60, etc. Then ans could be lower. Good.
Now, test scenario where we have inbound cheap only after some day, and outbound cheap only before some day, and we need to choose L that fits. Our algorithm covers.
Now, one more nuance: The pref and suff arrays are computed for every day, but we only use pref[L-1] and suff[L+k]. So we could compress by only storing needed values? Not necessary.
Now, corner case: What if k = 0? Not allowed.
Now, check if there is any hidden condition about multiple jury members from same city? No, exactly one per city.
Now, is there any possibility that a jury member could take more than one inbound flight (e.g., flight from city to some other city then to Metropolis)? No, because flights only go to/from Metropolis; there are no flights between non-zero cities. So direct flights only.
Thus the solution stands.
Now, we should verify with a tricky case: When there are multiple flights for a city, and the cheapest inbound is on a later day, but we might be forced to pick an earlier more expensive inbound if we choose an early L. That's captured by pref[T] being higher for small T. So the minimization over L will find the best trade-off.
Now, potential performance: For max_day up to 1e6, loop L up to 1e6. That's okay. However, if k is small (like 1), then L up to 999,999, which is fine.
Now, what about if max_day is 1e6 and k=1, L up to 999,999. That's 1e6 iterations, each constant time, fine.
Now, ensure we use fast I/O.
Now, edge case: n=1e5, m=1e5, all inbound flights for each city may be many. The updates per flight are O(1). Good.
Now, we should consider that some cities may have no inbound or outbound flights. Then pref or suff never become finite. That's fine.
Now, potential bug: In pref computation, we set pref[day] = totalIn if coveredIn == n else INF. But after we have covered all cities, pref[day] for later days may be same. However, what about days before the first day when we achieve coveredIn == n? Those days have INF. That's correct.
Now, for suffix, similar.
Now, but note: In suffix, we might achieve coveredOut == n at some day (i.e., from that day downward). For days lower than that, coveredOut remains n. That's fine.
Now, we also need to consider that the flights days are integers. However, the work days are also integer days. Good.
Now, there's a nuance: "It is allowed for jury member to stay in Metropolis for more than k days." Already covered.
Now, verify with sample test 1 as coded.
Now, test with a case where inbound flights are all on day 1 except one on day 10, and outbound flights all on day 20 except one on day 5. Then possible? Let's do n=2. City1 inbound day1 cost10, outbound day20 cost10; City2 inbound day10 cost10, outbound day5 cost10. Here outbound for city2 day5 is before any possible L? For L to work, need outbound > R. If we choose L such that R < 5? But then inbound for city2 must be < L, but city2 inbound is day10, so L must be >10. But then outbound for city2 is day5, which is < L, so fails. So impossible. Our algorithm: inbound: pref[T] becomes finite when T >=10? Actually for city2 inbound day10, so pref[T] for T<10 missing city2 => INF. For T>=10, pref[T] = 20? Actually city1 cost10, city2 cost10 =>20. outbound: city1 day20, city2 day5. For suffix, we need both outbound. For U <=5, both flights qualify (day5 and day20) => total=20. For U=6..20, only city1 qualifies? Actually for U=6, flights with day >=6: city1 day20 (qualifies), city2 day5 (no) => missing city2 => INF. For U=21, none? Actually only day20, so missing city2 -> INF. So suff[U] finite only for U <=5. Then we need L such that pref[L-1] finite and suff[L+k] finite. pref finite requires L-1 >=10 => L>=11. Then suff[L+k] finite requires L+k <=5 => L <= 5 - k, impossible for k>=1. So no L. Answer -1. Good.
Now, test a case where both are possible but only for specific L. Example: n=2. Inbound: city1 day1 cost10, city2 day10 cost10. Outbound: city1 day5 cost10, city2 day20 cost10. k=5. Let's see feasibility: Need L such that inbound1<L (day1<L -> L>1), inbound2<L (day10<L -> L>10). So L>=11. Outbound1 > L+4? Actually R = L+4 (since k=5: days L..L+4). So need outbound1 > L+4 and outbound2 > L+4. outbound1 day5, if L>=11, then outbound1 day5 is < L+4 (since L+4 >=15), so fails. So impossible. But maybe L=11: outbound1 day5 is < 15, fail. So answer -1. Our algorithm: pref[T] finite for T>=10 (L-1>=10 => L>=11). suff[U] finite? For outbound: city1 day5, city2 day20. For U = L+k = L+5. For L>=11, U >=16. For U=16, flights with day>=16: city2 day20 qualifies, city1 day5 not => missing city1 => INF. So no L. Good.
Now, test a feasible case: n=2. Inbound: city1 day1 cost10, city2 day5 cost10. Outbound: city1 day9 cost10, city2 day12 cost10. k=3. Need L such that inbound1<L, inbound2<L -> L>5 => L>=6. Also outbound1 > L+2, outbound2 > L+2. If L=6, R=8, need outbound1>8 (day9 OK), outbound2>8 (day12 OK). So L=6 works. Also L=7: R=9, outbound1>9? day9 not >9, so fails. So only L=6 works. Our algorithm: pref: for T>=5, pref[T]=20. So pref[5] =20? Actually pref[5] would be? At day5, after processing inbound day5 for city2, both cities covered => total=20. So pref[5]=20. For L=6, pref[5]=20. suff: outbound flights day9 and day12. For U = L+k =9. For U=9, flights with day>=9: both city1 day9 and city2 day12 => total=20. So suff[9]=20. Sum=40. For L=7, pref[6]=20, U=10, suff[10]? flights day>=10: city2 day12 qualifies, city1 day9 not => INF. So ans=40. Good.
Now, check if there is an alternative with different costs? Not needed.
Now, we need to consider that the answer may be large, but within 64-bit.
Now, check for potential off-by-one errors.
The condition is arrival_day < L and departure_day > R. Our mapping: T = L-1 (since arrival_day ≤ L-1), U = R+1 = L+k (since R = L+k-1). So it's correct.
Now, consider L such that L=2, then T=1, U=2+k. For inbound, need arrival ≤1. For outbound, need departure ≥ L+k = 2+k. That's fine.
Now, test with L=2 in the example where inbound on day 1 and outbound on day L+k? allowed.
Now, confirm that suff[U] includes flights exactly on day U. Because if departure day = U, then it is ≥ U, so allowed. So yes.
Now, check that pref[T] includes flights exactly on day T, because arrival day = T ≤ L-1, so allowed. Yes.
Now, the code seems correct.
Now, I'll implement.
Potential improvements: If we want to reduce memory, we could compute pref and suff as arrays of size max_day+2. But we already did.
Now, we should handle the case where max_day might be 0 (if m=0). Then we cannot have any flights. Answer -1. So before allocating arrays, we should check if max_day == 0, then output -1. Actually if m=0, max_day remains 0. Then we cannot gather anyone. So output -1. But our code: vector pref(max_day+2) with max_day=0 => size 2, okay. But later we loop L from 1 to max_day - k, but max_day - k is negative, so loop not executed, ans stays INF, output -1. That's fine. However, we also compute pref and suff arrays over days 1..0? The for loops for day=1 to max_day will not execute (since max_day=0). So pref all INF. That's fine. But we also sort inbound and outbound (both empty), fine. So the code would work without special case. However, the allocation of vectors with size based on max_day might be small. But note: max_day might be 0, but we also need to consider that we might later access pref[L-1] where L-1 could be 0, which is within pref size (0..0+2). So okay. So we don't need special case.
But one thing: We used vector inbound, outbound. Sorting empty is fine.
Now, but there is a nuance: In the loop for L, we need to ensure L + k <= max_day. If max_day is 0 and k=1, condition fails, loop does nothing. So ans INF, output -1.
Now, test with n=1, m=0, k=1 => -1. Good.
Now, final code.
But we need to be careful about the input constraints: m can be 0, up to 1e5. So handle.
Now, ensure we use long long for total and cost.
Now, confirm that the update logic for total is correct when a cheaper flight appears after a more expensive one. We do:
But note: If we process multiple flights on the same day for the same city, the order matters? For example, we have two flights on same day: cost 10 and cost 5. They both have day = d. When we process them in the while loop, we will process them in the order they appear in the sorted list. But since we sorted only by day, not by cost, they may appear in any order. If we first process cost 10, minIn[city] is INF initially, so we set minIn[city]=10, covered++, total+=10. Then we process cost 5, see cost 5 < 10, then we go to else branch: totalIn += 5 - 10 = -5, total becomes 5, and minIn becomes 5. So final total is 5, correct. If we process cost 5 first, minIn becomes 5, total=5, then cost 10 is not <5, so ignored. So final total 5. So correct.
Now, what about inbound flights for the same city on different days? The prefix algorithm ensures we consider the cheapest among all flights with day ≤ current day. Since we process days in order, if we see a cheap flight later, we update total accordingly. That's fine.
Now, similar for suffix.
Now, check for overflow in totalIn addition: totalIn could become up to n*1e6 = 1e11, well within 64-bit.
Now, finalize code.
But we need to note: The flights may include both inbound and outbound for same city; we separate them.
Now, I will produce final answer.
But before final, let's consider if there is any alternative interpretation: Could a jury member take multiple flights? Possibly to return home, they could take a flight from Metropolis to their city directly, as given. So no.
Now, about the day range: The work days must be consecutive k days. Could they be, for example, days 5,6,7,8,9? Yes.
Now, we should also consider if there is any possibility that we could choose different inbound and outbound flights for the same city such that the inbound flight arrives after the outbound flight? That would be nonsense because they would have to go back before they arrive. But our constraints A < L and D > R, with L and R such that L <= R, so A < L <= R < D, so automatically A < D. So no issue.
Now, we also need to ensure that the same flight cannot be used by multiple jury members? That's not relevant; each flight is a ticket; we purchase for each jury member separately.
Now, finalize.
But there is a nuance: The problem states: "Cost of the arrangement is defined as a total cost of tickets for all used flights." So if two jury members take the same flight (same plane), they'd each need a ticket; cost is per ticket. So sum is fine.
Now, think about whether it's possible that a jury member might need to take a flight that is not directly from his city to Metropolis? Since there are no flights between non-zero cities, only direct flights to/from Metropolis. So they must take direct flights. So our approach is correct.
Now, confirm that the flights are one-way. Yes.
Now, code.
But wait: The problem says "All flights in Metropolia are either going to Metropolis or out of Metropolis." So indeed only those.
Now, test with a more complex scenario to ensure the algorithm doesn't miss something: Suppose we have inbound flights for all cities, but the cheapest inbound for some city is on a very late day. And outbound flights for all cities, but the cheapest outbound for some city is on a very early day. Then it might be impossible to find L satisfying both. The algorithm will detect because pref[T] becomes finite only after T >= some day, and suff[U] finite only for U <= some day. Intersection may be empty.
Now, what about the scenario where there is a city with multiple inbound flights, some cheap but later, and multiple outbound flights, some cheap but earlier. The optimal L may be somewhere in the middle. Our algorithm tries all L.
Now, complexity: O(max_day + m log m). With max_day up to 1e6, it's fine. But note that days can be up to 1e6, but also could be up to 10^6? Yes.
Now, we might even compress days by considering only days where flights occur, but we need contiguous range for L. However, L can be any integer day. So we need to consider all days. 1e6 is fine.
Now, final code as above.
But there is a small optimization: Instead of storing pref and suff for all days, we could compute ans while sweeping L? But simpler to compute arrays.
Now, let's double-check the indexing for suff: We defined vector suff(max_day + 3, INF). We compute for day from max_day down to 1. suff[day] is set. For day = max_day+1, we didn't set, but it's INF by default. In the loop, we use suff[L+k] where L+k may be max_day+1? Not allowed because L+k <= max_day by loop condition. So safe.
Now, we also need to consider the possibility that L+k = max_day+1 could occur if we incorrectly set loop condition to L+k <= max_day? Already ensured L+k <= max_day, so U <= max_day. So safe.
Now, what about L-1 maybe negative? L starts at 1, so L-1 >=0. So pref[0] exists.
Now, done.
Now, I will provide final answer code in final channel. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
struct Flight {
int day, city, cost;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m, k;
cin >> n >> m >> k;
vector<Flight> inbound, outbound;
int max_day = 0;
for (int i = 0; i < m; ++i) {
int d, f, t, c;
cin >> d >> f >> t >> c;
max_day = max(max_day, d);
if (t == 0) { // flight from city f to Metropolis
inbound.push_back({d, f, c});
} else { // flight from Metropolis to city t
outbound.push_back({d, t, c});
}
}
// ----- prefix: cheapest total cost to have all arrived by day T -----
sort(inbound.begin(), inbound.end(),
[](const Flight& a, const Flight& b) { return a.day < b.day; });
vector<ll> pref(max_day + 2, INF);
pref[0] = INF; // impossible, because days start at 1
vector<ll> minIn(n + 1, INF);
int coveredIn = 0;
ll totalIn = 0;
size_t idx = 0;
for (int day = 1; day <= max_day; ++day) {
while (idx < inbound.size() && inbound[idx].day == day) {
int city = inbound[idx].city;
ll cost = inbound[idx].cost;
if (cost < minIn[city]) {
if (minIn[city] == INF) {
coveredIn++;
totalIn += cost;
} else {
totalIn += cost - minIn[city];
}
minIn[city] = cost;
}
++idx;
}
if (coveredIn == n) {
pref[day] = totalIn;
}
}
// ----- suffix: cheapest total cost to have all depart on or after day U -----
sort(outbound.begin(), outbound.end(),
[](const Flight& a, const Flight& b) { return a.day < b.day; });
vector<ll> suff(max_day + 3, INF);
vector<ll> minOut(n + 1, INF);
int coveredOut = 0;
ll totalOut = 0;
int idxOut = (int)outbound.size() - 1;
for (int day = max_day; day >= 1; --day) {
while (idxOut >= 0 && outbound[idxOut].day == day) {
int city = outbound[idxOut].city;
ll cost = outbound[idxOut].cost;
if (cost < minOut[city]) {
if (minOut[city] == INF) {
coveredOut++;
totalOut += cost;
} else {
totalOut += cost - minOut[city];
}
minOut[city] = cost;
}
--idxOut;
}
if (coveredOut == n) {
suff[day] = totalOut;
}
}
// ----- try every possible first work day L -----
ll answer = INF;
for (int L = 1; L + k <= max_day; ++L) {
ll incost = pref[L - 1];
ll outcost = suff[L + k];
if (incost != INF && outcost != INF) {
answer = min(answer, incost + outcost);
}
}
if (answer >= INF) {
cout << "-1\n";
} else {
cout << answer << "\n";
}
return 0;