class Solution {
public:
// Make vector of cities, where cities[idx] = destination city. So cities
// starts as cities = {1, 2, 3, 4, ...};
// For each query, we'll be removing edges between startQ and endQ and replacing these
// edges with one edge. (I think of the first edge as being removed and then replaced with
// the new long edge.)
// So we start with n-1 edges from city 0 to city n-1.
// For each query, do not take away the edge from city startQ, replace it with an edge to city qEnd.
// In other words, don't increase @takeAway for the first city.
// For all other cities, do delete an edge, (increate @takeAway).
// As we travel from qStart to qEnd update that city's next city. So city[idx] = qEnd.
// In future queries, we travel along the new edges, deleting edges as we go. Where do we go?
// Where ever cities[idx] tells us to.
// The "no query rule": "There are no two queries such that queries[i][0] < queries[j][0] <
// queries[i][1] < queries[j][1]."
// So, for every query, cities between qStart and qEnd are essentially removed. But what if
// qStart is on one of these removed cities? That can never happen according to the description.
// Well, it could happen, but then the current query will be a nested query (nested inside a
// previous query). In that case, simply continue to the next query. Doesn't change the number
// of edges from city zero to end.
// What if qStart starts before any previous qStarts, but ends at a previously removed city?
// Again, not possible according to the description.
// Essentially, if there is a query, we should remove all EXISTING edges between the qStart and qEnd.
// So, update all edges as we travel, and count the removed edges.
vector<int> shortestDistanceAfterQueries(int n, vector<vector<int>>& queries) {
// vector of cities and their destinations.
vector<int> cities(n, 0);
iota(cities.begin(), cities.end(), 1);
// Answer.
vector<int> ans(queries.size(), -1);
// Edges removed so far.
int subtrahend = 0;
// For each query.
for(int ii=0; ii<queries.size(); ++ii)
{
int qStart = queries[ii][0];
int qEnd = queries[ii][1];
// Edges removed in this query.
int takeAway = 0;
// idx is from range [qStart, qEnd)
int idx = qStart;
while(idx < qEnd)
{
// Do not takeAway an edge for the qStart city (it's replaced). But do mark it with qEnd.
if (idx == qStart)
{
// Don't update with this city with a shorter edge. A longer edge already exists.
if (qEnd < cities[qStart]) // if (cities[qStart] != qStart + 1)
{
break;
}
else
{
// temp is the next city, which will have the next edge that needs to be taken away.
int temp = cities[idx];
// update cities[idx].
cities[idx] = qEnd;
// go to next city to remove that edge.
idx = temp;
}
}
// Else not the startCity, so do increase @takeAway.
else
{
int temp = cities[idx];
cities[idx] = qEnd;
idx = temp;
++takeAway;
}
}
subtrahend += takeAway;
// Original number of edges was n-1.
ans[ii] = n - 1 - subtrahend;
}
return ans;
}
};