We need to assign labels (a permutation) to vertices such that for each directed edge v->u, label(v) < label(u). We want the lexicographically smallest permutation of labels when read as a sequence of n labels (presumably order by vertex index? Typically output is a list of n numbers, the label assigned to each vertex (vertex 1..n). Lexicographically smallest means we want to minimize the first element, then second, etc. But careful: The output is a permutation of labels assigned to vertices 1..n. So the sequence is (label[1], label[2], ..., label[n]). We need to choose a labeling satisfying constraints and minimizing this sequence lexicographically.
Constraints: Directed acyclic graph. Edge v->u requires label(v) < label(u). This is like a topological ordering constraint but reversed: Usually we assign numbers 1..n to vertices in a topological order: assign increasing numbers along the order. But here we want labels themselves to be a permutation; the condition label(v) < label(u) means if we think of labels as a topological order (i.e., if we order vertices by increasing labels, we get a topological order), that is, labels must be a topological numbering (a linear extension). Actually, any labeling that respects the partial order yields a topological sort if we sort vertices by label. Conversely, any topological order can be assigned labels 1..n according to that order.
But we want to minimize the sequence (label[1], label[2], ..., label[n]) lexicographically. That is different from finding the lexicographically smallest topological order of vertices (when outputting vertex order). Instead we fix the vertex indices (1..n) and assign them labels. The lexicographic order compares label[1] first; we want label[1] as small as possible, then label[2] as small as possible given that, etc.
We need to find a labeling that respects the DAG and minimizes the label vector.
We can think of the constraints: For each vertex v, label(v) must be at least something? There is also an upper bound: since labels are a permutation, the sum is fixed. To minimize label[1], we want to assign small labels to earlier indexed vertices, but subject to constraints.
This is reminiscent of problem: "assign numbers 1..n to nodes of DAG with precedence constraints, minimize lexicographically the label vector". This might be solved by a greedy approach but careful.
Let's formalize:
We need a bijection f: V -> {1,...,n} such that for each edge (v,u): f(v) < f(u). We want to minimize f(1), then f(2), ..., f(n) lexicographically.
Observation: Since f is a permutation, the multiset of values is fixed. The constraints are partial order constraints. The lexicographic minimization over the vector (f(1),...,f(n)) is similar to: we want to assign the smallest possible number to vertex 1, subject to constraints, then to vertex 2 given that, etc.
But we must ensure that we can assign the remaining numbers to the remaining vertices respecting constraints.
This is like a scheduling problem: we need to assign numbers (ranks) to items with precedence, and we care about specific ordering of items (by index). This is different from finding a topological order: there, we output an ordering of vertices (list of vertices). Lexicographically smallest topological order means that we output vertices in an order such that the sequence of vertex indices is as small as possible; that is achieved by always picking the smallest-indexed vertex with zero in-degree. But here we output labels for fixed vertices; we want the labels themselves to be lexicographically small.
We need to transform the problem.
Let's denote the labels as values 1..n. The condition f(v) < f(u) means that f respects the partial order. If we consider the inverse permutation g: {1..n} -> V where g(k) = vertex with label k. Then the condition becomes: for every edge v->u, f(v) < f(u) => the vertex v appears before vertex u in the ordering g (since label order = position in ordering). So g is a topological order of the DAG. And f is the inverse of g: f(v) = position of v in that topological order.
Now, we want to minimize the vector (f(1), f(2), ..., f(n)) lexicographically. Equivalent: we want to choose a topological ordering g (a permutation of vertices respecting edges) such that the positions of vertices 1..n in that ordering form a lexicographically smallest vector (when ordered by vertex index). That is, we want to assign early positions to low-index vertices as much as possible, but subject to topological constraints.
So the problem reduces to: Find a linear extension (topological ordering) of the DAG that minimizes the sequence of positions of vertices sorted by vertex index. That is, we want to minimize the rank of vertex 1, then vertex 2, etc.
We can think of it as we have to assign each vertex a rank (1..n) respecting partial order. We want to minimize lexicographically (rank[1], rank[2], ..., rank[n]).
This is similar to "lexicographically smallest topological order" but with different objective. Usually lexicographically smallest topological order means output order of vertices; we want output order (g(1), g(2), ...) to be lexicographically smallest. Here, we want the order of vertices by index to have smallest possible ranks.
Alternatively, we can see it as we want to assign small ranks to low-index vertices, but ensuring that if a low-index vertex has outgoing edges, its rank must be less than its descendants, so maybe we need to assign even smaller ranks to those descendants? Actually, for vertex v, to make f(v) as small as possible, we would like to put v early. However, if v has outgoing edges to many vertices, those must come after v, so they need larger ranks; but that doesn't conflict with making v's rank small. On the other hand, if v has incoming edges, then predecessors must have smaller ranks; that could force v's rank to be larger if its predecessors are forced to be later? Wait, if v has incoming edges from some u, then u must have smaller rank than v. So to minimize v's rank, we need its predecessors to have even smaller ranks. But if those predecessors are high-index vertices, they might be forced to have larger ranks due to other constraints? Actually, we can assign any rank as long as constraints are satisfied; we want to minimize f(1), f(2), ... in that order.
This is reminiscent of "minimum lexicographic labeling" under constraints, which can be solved by a greedy algorithm using a priority queue on vertices, but with a twist: we want to assign smallest possible numbers to vertices in order of their indices. This can be done by considering the reverse topological order: assign the largest numbers last. Often, for minimizing the sequence of labels, we can assign labels from n down to 1 using a topological order on the reverse graph. Let's explore.
Consider we want to minimize label[1]. The smallest possible value is 1. Can we assign label 1 to vertex 1? Only if no incoming edge forces a smaller label for some vertex that must be assigned 1? Actually, constraints: if there is an edge u->1, then label(u) < label(1). So if there is any predecessor of 1, label(1) must be greater than all labels of its predecessors. The smallest label any vertex can have is 1. So vertex 1 can have label 1 only if it has no incoming edges (i.e., no vertex v with v->1). If there is any incoming edge, then label(1) must be at least 2, but maybe we can assign label 1 to a predecessor? However, if predecessor is some other vertex, we might assign label 1 to it, and then label(1) could be 2. But is it forced that label(1) cannot be 1 if there is an incoming edge? Yes, because then that predecessor must have a label smaller than label(1), so label(1) > label(predecessor) >=1, so label(1) >=2. So vertex 1 can have label 1 only if indegree(1)=0.
But also consider: if vertex 1 has outgoing edges, that's fine: its successors must have larger labels.
So to minimize label[1], we should assign the smallest available number to vertex 1 if possible under constraints. If not possible, we have to assign a larger number.
However, we also need to assign a permutation. So maybe the optimal strategy is: we will assign labels from 1 to n in some order to vertices. The assignment must satisfy that if v->u then v gets a smaller label than u. This is exactly a linear extension. So we need to order vertices (the order in which we assign increasing labels) as a topological order. So picking which vertex gets label 1 is equivalent to picking a source vertex (indeg=0) in the DAG? Actually, the vertex with label 1 must have no incoming edges in the DAG? Not necessarily: If there is an incoming edge from some vertex w, then w's label would have to be less than 1, impossible. So yes, label 1 can only go to a source vertex (indegree 0). More generally, the set of vertices that can receive label k are those that have all predecessors already assigned labels < k. So to assign labels from 1 upward, we must repeatedly pick a vertex with all predecessors assigned. That is exactly performing a topological sort: assign label cur = 1, pick a vertex from the current set of vertices with no unassigned predecessors (i.e., whose indegree in the remaining graph is 0) and assign cur, then increment cur.
Thus, any labeling respecting constraints corresponds to a topological order: the order of assignment of increasing labels.
Therefore, constructing a labeling is equivalent to choosing a topological order (the order in which we assign labels 1,2,...,n). So the problem reduces to: choose a topological order π (a permutation of vertices) such that if we let f(v) = position of v in π (1-indexed), then the vector (f(1), f(2), ..., f(n)) is lexicographically smallest.
Now, note that this is not the same as the topological order that is lexicographically smallest when outputting vertices. In that case, we would pick the smallest-index vertex among available sources each time. That yields a topological order that is lexicographically smallest in terms of the order of vertices. But does that correspond to minimizing f(1), f(2), ...? Not necessarily. Let's test with examples.
Example 1:
n=3, edges: 1->2, 1->3, 3->2. Graph: 1 and 3? Actually edges: 1->2, 1->3, 3->2. So DAG: 1 and 3 precede 2; also 1 precedes 3? No, 1->3 also, so 1 precedes 3 precedes 2? Wait, 1->3 and 3->2, so 1 precedes 3, and 3 precedes 2. So full order: 1,3,2. That is a valid topological order. Also 1,2,3? No, because 3->2 violates if 2 before 3? Actually 3->2 requires 3 before 2, so 2 cannot be before 3. So only topological orders: 1,3,2 (since 1 must be before 3 and 3 before 2). So the only topological order is [1,3,2]. Thus f(1)=1, f(2)=3, f(3)=2. Output: 1 3 2. That matches example output.
Example 2:
Input:
4 5
3 1
4 1
2 3
3 4
2 4
Let's list edges:
3->1
4->1
2->3
3->4
2->4
Interpret: nodes: 2->3, 2->4, 3->4, 3->1, 4->1. So constraints: 2 before 3 and 4; 3 before 4 and 1; 4 before 1. So partial order: 2 before 3 before 4 before 1? Also 2 before 4 directly. And 3 before 1, 4 before 1. So 2 is earliest, then 3, then 4, then 1. That's one topological order: 2,3,4,1. Are there others? Possibly 2,3,4,1 only? Let's see: 2 must come first because it has no incoming? Incoming to 2? none. So 2 is source. After 2 removed, edges: 3->4, 3->1, 4->1. Then sources: 3? 3 has incoming from 2, but removed so indegree becomes 0? Actually after removing 2, the edges from 2 are gone. So indegree of 3 becomes 0 (since only incoming from 2 removed). Also indegree of 4? original incoming from 2 and 3, after 2 removed, still incoming from 3 remains, so indegree 1. So only source is 3. So must pick 3 next. After 3 removed, edges: 4->1. Then source: 4 (incoming from 2 and 3 removed). So pick 4. Then 1. So indeed only one topological order: 2,3,4,1. So f(1)=4, f(2)=1, f(3)=2, f(4)=3. Output would be: 4 1 2 3, matches example.
Example 3:
Input:
5 4
3 1
2 1
2 3
4 5
Edges:
3->1
2->1
2->3
4->5
So partial orders: 2 precedes 1 and 3; 3 precedes 1; and 4 precedes 5. So components: one with {1,2,3} and separate {4,5}. In component 1, possible topological orders: 2,3,1 or 2,1,3? Wait, 3 precedes 1, so after 2, we can do 3 then 1, or could we do 1 before 3? No, because 3->1 means 3 before 1, so 1 cannot be before 3. So order must be 2,3,1. That's fixed? Also could we do 2,3,1 only. In component 2: 4,5. So overall many topological orders: we can intermix the two linear chains arbitrarily as long as internal constraints hold. For example: 2,3,1,4,5 or 2,3,4,1,5 or 2,4,3,1,5? Check: 4 can be before 3? Yes, no constraints between them. Similarly, 5 must be after 4, but can be anywhere after 4. So many orders.
Now output example: 3 1 2 4 5. Let's compute f from that: f(1)=? Output is "3 1 2 4 5": label for vertex1 =3, vertex2=1, vertex3=2, vertex4=4, vertex5=5. So that corresponds to topological order where vertices are assigned labels increasing. The order of vertices by label (positions) would be: label1: vertex2, label2: vertex3, label3: vertex1, label4: vertex4, label5: vertex5. So topological order = [2,3,1,4,5]. Is that lexicographically smallest vector (f(1), f(2), f(3), f(4), f(5)) = (3,1,2,4,5)? Let's see if we can get a smaller lexicographically. We want to minimize f(1) first. Could f(1) be 1? Vertex1 has incoming edges from 2 and 3, so its label cannot be 1 because its predecessors must have smaller labels. So minimal label for vertex1 is at least 3? Actually predecessors: 2 and 3. They must have labels < label(1). The smallest possible for label(1) if we assign labels 1,2 to 2 and 3 in some order? The smallest possible label(1) is 3 because you need two smaller distinct labels for 2 and 3. But could we assign label(1)=2? Then labels for 2 and 3 must be <2, i.e., only label 1 available for one of them, but both need labels less than 2? Actually both 2 and 3 must have labels less than label(1). If label(1)=2, then both 2 and 3 must be assigned label 1? impossible because they are distinct. So indeed label(1) >=3. Minimum is 3. So f(1)=3 is optimal.
Next, given f(1)=3, minimize f(2). f(2) can be 1? Possibly. In order to have f(1)=3, we need assign labels 1 and 2 to vertices 2 and 3 (since they are the only ones that must be less than vertex1). Also vertex2 has no incoming? Actually vertex2 has no incoming edges? Edges: 2->1, 2->3. So vertex2 has no incoming edges (no one points to 2). So it can be label 1. So f(2)=1 is possible. Then f(3) would then be 2 (since label(3) must be < label(1) and >? Actually 2->3, so label(2) < label(3). If label(2)=1, then label(3) must be >1, and also < label(1)=3, so label(3) can be 2. So f(3)=2 is forced if we set f(2)=1 and f(1)=3. So far (3,1,2,...). Then vertices 4 and 5: we need to assign labels 4 and 5. They have no constraints with others, except 4->5. So we could assign label(4)=4, label(5)=5, or label(4)=5, label(5)=4? But 4->5 requires label(4) < label(5), so label(4)=4, label(5)=5. So (4,5) order fixed. So the vector (3,1,2,4,5) is indeed lexicographically minimal. Could there be a labeling with f(1)=3, f(2)=1, f(3)=2, f(4)=4, f(5)=5, which is exactly the example. So it matches.
Thus the examples align with the interpretation.
Now we need to find algorithm for n up to 1e5, m up to 1e5.
We need to assign labels (positions) to vertices respecting DAG, minimizing (f(1), f(2), ..., f(n)).
Observations: This is like we want to assign the smallest possible positions (labels) to vertices with lower indices, subject to constraints. One approach: we can decide the order in which we assign labels from 1 to n (i.e., the topological order) in a way that "prioritizes" vertices with smaller indices? But careful: We want to minimize f(1) first. That means we want vertex 1 to be as early as possible in the topological order. In other words, we want vertex 1's position to be as small as possible. Similarly for vertex 2, after fixing the smallest possible position for vertex 1, we want vertex 2's position as small as possible, etc.
So we need to find a linear extension that minimizes the positions of vertices in order of vertex index.
This is similar to the problem: given a poset, find a linear extension that minimizes a weighted sum? Not exactly.
We can think of it as: we have to order vertices. For each vertex i, we care about its rank. Lexicographic minimization over ranks of 1..n. This is like we assign a priority to each vertex (its index), and we want to minimize the vector of ranks sorted by priority. This is akin to the notion of "minimum linear extension with respect to lexicographic order on the identity labeling". There is known approach: Process vertices in order from n down to 1 assigning largest labels? Or maybe we can assign labels from n down to 1 using a topological order on the reversed graph with a max-heap on vertex indices? Let's test.
Often, to get lexicographically smallest topological order (outputting vertices), we use a min-heap on vertex indices among sources. To get lexicographically largest topological order, we use max-heap. But here we want to minimize the rank of vertex 1, then vertex 2, etc. This might be achieved by processing the topological order in reverse: assign the largest label n to a vertex that can be placed last, but choose which one to maximize something? Let's think.
We need to determine the position (label) for each vertex. Since labels are 1..n, we can decide which vertex gets label n, then n-1, etc. The condition f(v) < f(u) for v->u means that if v precedes u, then v gets smaller label. So if we assign labels from largest to smallest (i.e., decide who gets label n, then n-1, ...), then when we assign label k, we are essentially choosing a vertex that can be placed at position k in the order, i.e., it must have no successors that are still unassigned? Actually, in the reverse topological order, we can take sinks (vertices with no outgoing edges) and assign them the largest remaining label, because they can be last in the order. More precisely, if we have a DAG, a valid linear extension can be constructed by repeatedly removing a sink (vertex with out-degree zero) and placing it at the end of the order (i.e., assign the largest remaining label). This is the reverse of the usual source-removal algorithm. The set of vertices that can be placed last are those with no outgoing edges to unassigned vertices (i.e., all successors already placed). So to assign labels from n down to 1, we can maintain a set of candidate sinks (out-degree zero in the current subgraph). At each step, we choose one vertex from this set to assign the current largest label, remove it, and update its predecessors (decrease their out-degree? Actually, when we remove a vertex, we consider its incoming edges: for each predecessor, its out-degree reduces; if it becomes 0, it becomes a sink and can be candidate for next step). This is the canonical algorithm for topological sorting in reverse using a queue/set of sinks.
Now, we need to decide which sink to assign the current largest label at each step, to achieve the lexicographically smallest f vector. Since we assign labels from largest to smallest, the choice of which vertex gets the large labels will affect the smaller labels later. We want to minimize f(1) (i.e., position of vertex 1) - that means we want vertex 1 to get as small a label as possible, i.e., we want it to be assigned early in the forward process, which means in the reverse process we want to postpone assigning vertex 1 until later (so that it gets a smaller label). Actually, forward: we assign label 1 first to a source, then label 2, etc. Reverse: we assign label n last to a sink, then n-1, etc. To minimize f(1), we want vertex 1 to be as early as possible, i.e., have a small label. In reverse, that means we want to assign a large label to vertex 1? No, if vertex 1 gets a small label, it will be assigned early in forward, i.e., it will be removed early from the set of sources. In reverse, we are assigning large labels to sinks. Vertex 1 being early in forward means it's not a sink (unless it's isolated) and will be removed early; in reverse, it will be assigned a label early? Let's be precise.
Two equivalent ways:
- Forward process: start with sources, assign label cur=1 to some source, remove it, update, repeat. The order of assignment (the order in which we pick vertices) gives the topological order (position = label).
- Reverse process: start with sinks, assign label cur=n to some sink, remove it, update, repeat. The order of assignment (the order in which we pick vertices) gives the reverse topological order (position = n - order +1).
Now, if we want to minimize the rank of vertex 1, we want it to be assigned a small label, i.e., to be picked early in the forward process. That is equivalent to it being picked late in the reverse process? Actually, suppose forward order: pick v1 (label1), v2 (label2), ..., vn (label n). Reverse order: we pick u1 (label n), u2 (label n-1), ..., un (label 1). The forward order is the reverse of the reverse order (if we list reverse picks as w1 = u1 gets label n, w2 = u2 gets label n-1, etc., then the forward order is w_n, w_{n-1}, ..., w_1). So if we want vertex 1 to have small label (i.e., appear early in forward), that means it should appear late in the reverse sequence (since forward early = near the end of reverse). For example, if vertex 1 gets label 1 (smallest), then in forward it is picked first; in reverse, it would be the last picked (gets label 1). So to minimize f(1), we want vertex 1 to be assigned as late as possible in the reverse process (i.e., get a small label, i.e., assigned at the end of reverse process). But we assign labels from largest down to smallest; the later we assign in reverse, the smaller the label we give. So indeed, to give vertex 1 a small label, we want to postpone its selection as much as possible when assigning from n downwards. That suggests that when we are selecting a sink to assign the current largest label (say we are at step where we need to assign label X, which is the current largest remaining), we should avoid assigning vertex 1 if possible, because assigning it now gives it a large label, which is bad (since we want it small). Instead, we should assign large labels to vertices that we don't mind having large labels, i.e., vertices with higher indices? Because we care about lexicographic order over vertex indices: after minimizing f(1), we minimize f(2), etc. So we want vertices with smaller indices to have as small labels as possible. So in reverse, we want vertices with smaller indices to be assigned later (i.e., get smaller labels). So when selecting a sink to assign the current largest label, we should choose the sink with the largest index? Because giving a large label to a high-index vertex is less harmful for lexicographic order (since we care about low indices first). For example, if we have to assign label n, we want to give it to a vertex with as large index as possible, to preserve the chance to give smaller labels to low-index vertices later. That seems plausible.
Check with examples: Example 2: vertices: 1,2,3,4. The DAG: sources? Actually reverse process: we start with sinks. The sinks: vertex 1 (no outgoing? Let's see: edges: 3->1,4->1,2->3,3->4,2->4. Outgoing: 1 has none, 2 has outgoing to 3 and 4, 3 has outgoing to 1 and 4, 4 has outgoing to 1. So only sink is 1? Actually vertex 1 has no outgoing edges; vertex? 2? has outgoing to 3,4; 3 to 1,4; 4 to 1. So indeed only sink is 1. So initially only candidate sink is 1. In reverse process we assign label n=4 to a sink. The only sink is 1, so 1 gets label 4. That matches output f(1)=4. Then we remove 1, update: remove incoming edges to 1 from 3 and 4. Now after removal, check outgoing degrees: 2 still has outgoing to 3,4; 3 has outgoing to 4 (since edge 3->4 remains); 4 has no outgoing (since its only outgoing was to 1, now removed). So sinks now: 4. Assign label 3 to sink 4. So f(4)=3. Remove 4, update: remove incoming to 4 from 2 and 3. Now vertices: 2 and 3. Edges: 2->3? Actually there is edge 2->3, also 3->? None. After removing 4, 3 has no outgoing (since 3->1 and 3->4 removed). So sinks: 3 (and 2? 2 has outgoing to 3? Yes, 2->3 remains, so 2 still has outgoing, not sink). So assign label 2 to 3. f(3)=2. Remove 3, then 2 becomes isolated sink, assign label 1 to 2. f(2)=1. So reverse order: picks: 1,4,3,2 => labels 4,3,2,1. This yields f vector: 4,1,2,3. That matches output.
But note: in reverse, we had no choice: only sink at each step. So algorithm using "pick sink with largest index" would have done the same as forced.
Example 3: Let's simulate reverse with rule "pick sink with largest index" and see if we get output (3,1,2,4,5).
Graph: edges: 3->1,2->1,2->3,4->5. Outgoing:
1: none
2: to 1 and 3
3: to 1
4: to 5
5: none
Sinks: vertices with outdeg=0: 1 and 5. Among sinks, largest index is 5. So assign label 5 to 5. (Cur label =5)
Remove 5, update: remove incoming from 4. Now 4 becomes sink? 4 has no outgoing now? It had only edge to 5, so now outdeg 0. Sinks now: 1 and 4. Largest index =4, assign label 4 to 4.
Remove 4, update: no incoming (since no one points to 4 except maybe? Actually none). So sinks: 1 only? Also vertex 2 and 3 still have outgoing. 2->1,2->3; 3->1. So after removal, sinks: 1 (since outdeg 0) and maybe? 2 still has outgoing to 1,3; 3 still to 1; so only sink is 1. But wait, 3->1 still, so 1 is sink. Could 3 be a sink? It has outgoing to 1, so no. So only sink is 1. Assign label 3 to 1.
Remove 1, update: remove incoming edges from 2 and 3. Now vertices: 2 and 3. Edges: 2->3 (since 2->3 remains). So after removal, outdeg: 2->3, so 2 has outgoing, 3 has none. Sinks: 3. Assign label 2 to 3.
Remove 3, update: remove incoming from 2. Now 2 isolated, assign label 1 to 2.
Thus f: 1 gets label 3, 2 gets 1, 3 gets 2, 4 gets 4, 5 gets 5. That's exactly example output. Good.
So the reverse sink selection with largest index gave the correct result.
Now test example 1: Graph: 1->2,1->3,3->2. Outgoing:
1: to 2,3
2: none
3: to 2
Sinks: 2 only? Also maybe 3? No, 3 has outgoing to 2, so not sink. So only sink is 2. So assign label 3 to 2. Remove 2, update: remove incoming from 1 and 3. Then outdeg: 1->3, 3->? none. So sinks: 3. Assign label 2 to 3. Remove 3, update: remove incoming from 1. Then sink: 1, assign label 1. So f: 1->1, 2->3, 3->2. Output: 1 3 2, matches.
Thus the heuristic "assign largest labels to sinks with the largest vertex index" seems to produce the lexicographically smallest label vector.
We need to confirm that this greedy algorithm always yields the optimal lexicographic labeling.
Intuition: We are constructing a linear extension (topological order) by deciding which vertex goes last, then second last, etc. The lexicographic objective (minimize f(1), then f(2), ...) means we want vertices with smaller indices to have as small positions as possible, i.e., to be as early as possible. In reverse, that corresponds to wanting them to be as late as possible (since early in reverse => large label, which is bad). So to minimize f(i) for small i, we want to postpone assigning label to i as much as possible in the reverse process, i.e., we want to avoid giving it large labels. So at each step, when we have a set of candidate sinks (which can be placed at the current largest remaining label without violating constraints), we should give the large label to the candidate with the largest index (since we care less about large indices). That seems like a typical greedy exchange argument: If at some step we have two sinks i and j with i < j, and we assign the current largest label L to i (which yields f(i)=L) and later assign a smaller label l to j (f(j)=l), we could swap their assignments if feasible to possibly improve the lexicographic order? Let's examine.
Suppose we have two sinks i and j with i < j. If we assign label L (largest) to i, and later assign a smaller label to j, then f(i)=L (large), f(j)=l (small). Since i < j, the lexicographic order cares about f(i) first; having f(i)=L is worse than if we could make f(i) smaller. Could we instead assign L to j and later assign l to i? That would give f(i)=l (small), f(j)=L (large). Since i < j, the vector (..., f(i), f(j), ...) would be lexicographically smaller if l < L. However, we must check feasibility: after we assign L to j and remove it, does i remain a sink and later be assignable with l? Since both are sinks at the current step, they have no outgoing edges to unassigned vertices. If we assign L to j and remove it, does that affect i's sink status? Removing j could only affect i if there is an edge from i to j or j to i. But since both are sinks in the current subgraph, that means they have no outgoing edges to any remaining vertex. In particular, i does not have an edge to j (because if i had an edge to j, then i would not be a sink since it points to j which is still unassigned). So there is no edge i->j. Also, j->i cannot exist because j is a sink (outdeg 0) so no outgoing edges. So i and j are not connected by an edge (at least not i->j; could there be edge j->i? But j is sink, so no outgoing, so cannot have j->i). So they are incomparable. Therefore, swapping assignments is feasible: after removing j, i remains a sink (since it had no outgoing edges before, and removal of j doesn't add any outgoing edges). So we can assign i later. So giving the large label to the larger index is always beneficial (or at least not worse) for lexicographic order.
Thus greedy: always pick the sink with the largest index to assign the current largest label.
This is analogous to constructing a topological order by repeatedly removing the largest-index sink.
Hence the algorithm:
- Build adjacency list for outgoing edges (or incoming for reverse).
- Compute outdegree for each vertex (original direction: v->u means v has an outgoing edge to u).
- Also need to know for each vertex its list of predecessors (incoming edges) for update when we remove a vertex. Actually, in reverse process we remove sinks and then for each predecessor, we decrement its outdegree; if outdegree becomes 0, it becomes a sink and we add it to the candidate set.
- We'll use a max-heap (or a set) to maintain current sinks (vertices with outdegree == 0). Since we want to always pick the largest index among them.
- We'll assign labels from n down to 1: for step label = n down to 1:
- Pop the largest-index sink from the max-heap.
- Set label[vertex] = current_label.
- Decrement current_label.
- For each incoming edge (predecessor p of vertex) i.e., edges p->v, we decrement outdegree[p] by 1 (since we are removing v, which was a successor of p). If outdegree[p] becomes 0, push p into the heap.
- At the end, we have label for each vertex.
- Output labels for vertices 1..n in order.
Check complexity: O((n+m) log n) using heap.
We need to be careful: The graph is directed acyclic, but we have to consider the possibility of multiple edges? Problem says no multiple edges. So okay.
We must ensure that we have exactly n steps, and that the heap never becomes empty prematurely because the graph is acyclic and we start with all sinks present.
Edge Cases: If there is a vertex with outdegree 0 initially, it's a sink. But what if there are no sinks? In a DAG, there must be at least one sink (no cycles). Similarly, at each step after removal, new sinks appear.
Now, confirm that this algorithm indeed yields the lexicographically smallest permutation.
We already argued via exchange: At each step we assign the largest remaining label to the largest-index sink. Suppose there's an optimal solution that deviates at some step. Consider the first step (assigning label n) where optimal picks some sink v, but our algorithm picks w, with w > v (since we pick largest). Since both v and w are sinks, they are incomparable (no edge between them, as argued). Then swapping the labels of v and w in the optimal solution would give another valid labeling (since they are incomparable) and would produce a lexicographically smaller vector because we would reduce the label of the smaller-index vertex v (since it gets a smaller label) and increase label of larger-index w. So the optimal must also assign the largest label to the largest-index sink. By induction, the greedy yields the unique optimal labeling.
But we should ensure that swapping labels of v and w indeed maintains constraints. Since v and w are sinks at the time we assign label n, they have no outgoing edges to any unassigned vertices. In the full labeling, after assigning labels, the constraints that matter are only between pairs of vertices. For any edge x->y, we need label(x) < label(y). In the swapped assignment, if both v and w are not connected by an edge, swapping doesn't affect constraints involving them and others? Need to check constraints involving v or w with other vertices. Since v was a sink, it has no outgoing edges at all? Actually, sink means outdegree zero in the original graph. So v has no outgoing edges to any vertex. Similarly, w has no outgoing edges. So v and w only have incoming edges from some predecessors. Swapping their labels affects constraints of the form p->v and p->w. For any predecessor p of v, we originally had label(p) < label(v). After swapping, we need label(p) < new label(v) which is old label(w). Since label(w) > label(v) (because we swapped? Actually in optimal solution, v gets label n (largest), w gets some smaller label l < n. After swapping, v gets l, w gets n. For a predecessor p of v, originally we had label(p) < label(v)=n. That holds. After swap, we need label(p) < new label(v)=l. Is that guaranteed? Not necessarily, because label(p) could be between l and n. Since p is a predecessor of v, it must have label(p) < label(v) in any valid labeling. In optimal solution, we have label(p) < n. But could label(p) be >= l? Possibly. For example, suppose l is say 5, and label(p)=7. Then originally 7 < n holds; after swapping, we need 7 < 5 which fails. So swapping may break constraints with predecessors.
Ah! We need to be careful. Our earlier reasoning that v and w are incomparable and both sinks only means there are no edges between them. But they could have incoming edges from other vertices. In the current subgraph, they are sinks, meaning they have no outgoing edges, but they can have incoming edges. In the reverse process, when we assign label n to a sink v, we are essentially placing v last in the topological order. But if v has incoming edges, its predecessors must appear before v in the order, i.e., have smaller labels. That is satisfied because we assign labels to predecessors later? Wait, in reverse process, we assign largest labels first. When we assign v as sink with label n, we are determining that v is last. Then later we will assign labels to its predecessors, which will be smaller than n, so that's fine. However, if we swap v and w, making w last (label n) and v earlier (label l), we must ensure that all predecessors of v have labels less than l, not just less than n. In the optimal solution, w had label l, and its predecessors had labels less than l. But v's predecessors might have labels that are less than n but could be larger than l. So swapping might violate constraints for v's predecessors. So the simple exchange argument that swapping v and w always yields a feasible labeling is not obviously valid.
We need to re-evaluate. In our greedy, at step when we choose a sink to assign the largest remaining label, we consider the current subgraph (remaining vertices). At that moment, a sink vertex has outdegree 0 in the current subgraph, meaning it has no outgoing edges to any remaining vertices. However, it may have incoming edges from other remaining vertices. Those incoming vertices are not yet assigned labels; they will get smaller labels later. So if we assign the current large label to a sink v, we are essentially saying that all its predecessors will get smaller labels (since they will be assigned later). That is feasible as long as we can assign those predecessors later with labels less than v's label. Since we will assign decreasing labels, that's fine.
Now, suppose we have two sinks v and w with v < w (by index). Our greedy picks w (larger index) to give the large label. Could there be a scenario where picking v (smaller index) for the large label leads to a lexicographically better overall labeling? Let's test with a counterexample.
We need to consider the effect on predecessors. Perhaps giving a large label to a sink with many predecessors (especially low-index predecessors) might force those predecessors to have even smaller labels? Actually, if we give a sink a large label, its predecessors can get any smaller labels, which is easier because there is more room? Conversely, if we give a sink a small label (i.e., we postpone giving it label to later, meaning it gets a small label), then its predecessors must have even smaller labels, which might be more restrictive. Since we care about small labels for low-index vertices, we might want to give a small label to low-index vertices. So we want low-index vertices to be assigned late in reverse (so they get small labels). But if a low-index vertex is a sink, giving it a large label would be bad. So we want to avoid giving large labels to low-index sinks. That aligns with greedy: pick the sink with largest index to receive the large label.
But is it always optimal to pick the largest index sink? Could there be a situation where picking a lower index sink now could enable later assignments that lead to even smaller labels for other low-index vertices? For example, suppose we have two sinks: v (index 1) and w (index 2). Greedy picks w (index 2) to assign large label. Alternative: assign large label to v (index 1) and later assign a smaller label to w. Then f(1)=large, f(2)=small. Since we compare f(1) first, having f(1) large is worse than having f(1) small. So greedy is better. But could there be a case where picking v now might allow us to later give an even smaller label to vertex 1? No, vertex 1 is v itself, so we are assigning it large now, so f(1) becomes large, which is directly worse. So greedy's choice leads to f(1) smaller (since we give large label to w, not v). So for the immediate lexicographic comparison, picking the larger index sink seems beneficial for minimizing f(small-index) because it avoids giving large label to small-index vertex.
But what about vertices that are not sinks yet but might become sinks later? The choice of which sink we remove now can affect the set of sinks that become available later, and thus affect which vertices get which labels. For instance, by removing w, we might allow some low-index vertex to become a sink later and get a moderately sized label; but if we removed v instead, perhaps a different low-index vertex becomes a sink and gets a label that is even larger? This could affect the lexicographic order beyond the immediate comparison of the two sinks. We need to prove that greedy is optimal.
This is reminiscent of the problem "Assign numbers to nodes in a DAG to minimize lexicographically the vector of numbers for a fixed ordering of nodes" which can be solved by the "reverse topological sort with maximum priority queue". I've seen a known problem: "Label the vertices of a DAG with a permutation such that if there is an edge from u to v, then label(u) < label(v), and the labeling is lexicographically smallest when read as label[1..n]". The typical solution is to assign the largest numbers to the vertices with the largest numbers in the reversed graph using a max-heap of sinks. This is common in problems like "LEXICOGRAPHICALLY SMALLEST TOPOLOGICAL ORDERING" but not exactly; there is a Codeforces problem: "D. Labeling the Tree with a permutation" maybe? Actually, there is a problem "D. Minimum lexicographic permutation under constraints" often solved with reverse topological order with a max-heap.
Let's attempt a formal proof.
Let the labeling f be defined as per our algorithm: we produce an ordering π (the reverse of the order we pop from heap). Specifically, let order = [v_n, v_{n-1}, ..., v_1] be the order in which we assign labels n, n-1, ..., 1. Then f(v_i) = i? Wait careful: we assign label cur starting at n to the popped vertex. So the first popped gets label n, second gets n-1, ... last gets 1. So the topological order (from earliest to latest) is the reverse of popping order: vertices popped last have smallest labels. So the forward order (sorted by increasing label) is v_1 (popped last, label 1), v_2 (popped second last, label 2), ..., v_n (popped first, label n). So the positions: f(v_i) where v_i is popped at step? Actually better: Let the sequence of vertices popped (in order of decreasing label) be w_n, w_{n-1}, ..., w_1, where w_n gets label n, w_{n-1} gets n-1, ..., w_1 gets 1. Then the forward topological order (label 1 to n) is w_1, w_2, ..., w_n. So f(w_k) = k.
Our algorithm picks at each step the sink with maximum index to assign the current largest label. So w_n = max-index sink initially, w_{n-1} = max-index sink after removal, etc.
We claim this yields lexicographically smallest (f(1),...,f(n)).
Consider any optimal labeling f_opt. We want to show that the labeling from our algorithm f_algo is lexicographically <= f_opt.
We can prove by induction on the label value from n down to 1? Or consider the position of vertices in the order.
Alternative approach: The lexicographic minimization of (f(1),...,f(n)) is equivalent to maximizing the sequence (g(1),...,g(n)) where g(i) = n+1 - f(i) (i.e., the "reverse label") lexicographically? Since minimizing f(i) is same as maximizing the complement? Not exactly: if we define g(i) = n+1 - f(i), then lexicographically minimizing f (from left) corresponds to lexicographically maximizing g? Because if f1 < f2 then g1 > g2. So yes, minimizing f lexicographically is equivalent to maximizing g lexicographically. And g(i) are also a permutation of 1..n, and constraints f(v) < f(u) become g(v) > g(u). So we need a labeling g such that for each edge v->u, g(v) > g(u) (so it's a reverse topological order), and we want to maximize (g(1), g(2), ..., g(n)) lexicographically.
Now, g is like a ranking where larger numbers are better (we want g(1) as large as possible, then g(2), etc). And constraints: if v->u, then g(v) > g(u) i.e., v gets a larger number than u. That means in the reverse DAG (edges reversed), we have u->v implies g(u) < g(v)? Actually, if we reverse edges, we get a DAG where condition becomes: original edge v->u => in reversed graph, u->v, and we need g(v) > g(u) => g(u) < g(v). That's the same as original condition but with reversed edges. So g must be a topological ordering of the reversed graph (i.e., if we define reversed edges, then g respects that direction). Actually, original condition: v->u => f(v) < f(u). For g = n+1-f, we have v->u => g(v) > g(u). That means in the reversed graph (edge from u to v), we have u->v => g(u) < g(v)? Let's see: original edge v->u. Reverse edge: u->v. We want g(u) < g(v)? Because from g(v) > g(u) we get g(u) < g(v). So indeed, if we consider reversed graph, the condition becomes g(u) < g(v) for each reversed edge u->v. So g is a topological ordering of the reversed graph (i.e., it respects the direction of reversed edges). And we want to maximize lexicographically the vector (g(1),...,g(n)). That's a known problem: given a DAG (the reversed graph), we want the lexicographically largest topological order when outputting vertices in order 1..n? Actually, we want to assign numbers 1..n to vertices such that if there is an edge u->v in the reversed graph, then g(u) < g(v). And we want to maximize (g(1), g(2), ..., g(n)) lexicographically. This is similar to the standard problem of finding lexicographically largest topological order, but applied to the reversed graph and with the output being the label per vertex? Let's think.
In standard lexicographically largest topological order problem, we output the order of vertices (the sequence) such that it's lexicographically largest (i.e., we want the vertex with largest index to appear as early as possible). That is achieved by, when doing topological sort via source removal (forward), we use a max-heap on sources to pick the largest index source at each step. That yields a topological order that is lexicographically largest when reading the order as list of vertices.
But here we want to maximize the sequence (g(1),...,g(n)). Note that g is a labeling. To maximize g(1) first, we want vertex 1 to have as large a g-value as possible. Since g values are a permutation, the maximum possible g(1) is n. But constraints might prevent that. How to assign g? If we think in terms of topological order of the reversed graph, then g(v) is the position of v in that order? Actually, if we have a topological order π of the reversed graph (list of vertices from earliest to latest), we assign positions 1..n in that order. But then for an edge u->v in reversed graph, we need u before v, i.e., position(u) < position(v). That matches condition g(u) < g(v). So g can be the position in a topological order of the reversed graph. So g is a topological ordering of reversed graph.
We want to maximize (g(1),...,g(n)) lexicographically. That is, we want vertex 1 to have as large a position as possible (i.e., appear as late as possible in the topological order of reversed graph), then vertex 2 as large as possible given that, etc. So we want to produce a topological order of the reversed graph that is lexicographically largest when considering the sequence of positions? Actually, it's equivalent to: we want a linear extension (topological order) of the reversed graph that maximizes the vector of vertex indices sorted by position? Hmm.
But we can also think of constructing g by a greedy algorithm: to maximize g(1), we want vertex 1 to be as late as possible in the topological order. In the process of building a topological order (forward), we normally start with sources and assign increasing positions. To make a vertex appear as late as possible, we should delay its selection as long as possible, i.e., only take it when no other vertex is available. That suggests using a min-heap? Actually, consider the standard approach to get the lexicographically largest topological order: we use a max-heap on sources to pick the largest index source