At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.
The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that.
Input
The first line contains integer n (1 ≤ n ≤ 5000) — amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1 ≤ li < ri ≤ 106) — starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1).
Output
Output integer k — amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers — indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order.
Examples
Input
3
3 10
20 30
1 3
Output
3
1 2 3
Input
4
3 10
20 30
1 3
1 39
Output
1
4
Input
3
1 5
2 6
3 7
Output
0
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 need to parse problem: given n intervals [li, ri) or maybe inclusive? They say "If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect." So intervals are considered non-intersecting if one ends exactly when the other starts, i.e., intervals are like [l, r] but they don't intersect at the boundary. Usually such problems treat intervals as [l, r] and intersection if they overlap including boundaries? But statement clarifies that if one finishes and other starts at same moment, they don't intersect. So we can treat intervals as [l_i, r_i) or (l_i, r_i]? Usually we treat as half-open [l_i, r_i) to avoid intersection at boundary. So we assume intervals are half-open [l, r). But input integers, and l<r. Intersection means there exists time t such that two intervals both include t (including maybe only endpoints?). Since finishing time and starting time coincide do not count as intersecting, then we consider intervals as half-open: [l_i, r_i) works.
Goal: remove exactly one group (i.e., one interval) so that the remaining n-1 intervals are pairwise non-intersecting (i.e., no two overlap). We need to count and list all indices i such that after removing interval i, the rest are pairwise disjoint.
n up to 5000, which allows O(n^2) solutions possibly. But intervals: times up to 1e6, could use sweep, but n small. We need to determine for each i if the set of intervals without i is non-overlapping.
Brute force: For each i, check all pairs among the other n-1 intervals for overlap: O(n^3) (5000^3 too big). Better: compute some global condition.
Observation: The intervals after removal must be pairwise disjoint. That means the intervals (except i) must form a set of non-overlapping intervals. For a set of intervals to be pairwise disjoint, they can be sorted by start time and then each next start must be >= previous end (since boundaries allowed). So essentially, the intervals (except i) must be in a total order.
If initially there are no intersections, then removing any group still yields a set of non-intersecting intervals? Actually if initially no intersections, then all intervals are already pairwise disjoint. Removing any one will still keep them disjoint. So answer would be all indices. That matches sample 1: n=3, intervals: [3,10], [20,30], [1,3]. Note that [1,3] ends at 3, and [3,10] starts at 3 => they don't intersect. So all 3 are pairwise disjoint. Output 3 and all indices. Good.
But if there are intersections, we need to find which single removal can eliminate all intersections.
Essentially, we need to check for each i whether the set S_i = all intervals except i has no pairwise overlaps.
One approach: compute the "overlap graph" maybe. But we need to check if removing i makes the set pairwise non-overlapping.
Let's think: Condition for a set of intervals to be pairwise non-overlapping is equivalent to that when sorted by start, each end <= next start. Another way: The maximum number of intervals overlapping at any point must be 1. That is, depth <= 1.
So removing one interval, we need to reduce all depths to <=1. So we need to find intervals such that if we remove them, the remaining intervals have no overlapping pairs. That is, the intervals after removal have depth <=1. Initially, depth could be up to n.
We can compute for each point the number of intervals covering it. But times are up to 1e6, but n=5000, we could compress coordinates and compute frequencies. But maybe simpler: Since n is small, we could compute overlaps between intervals and identify intervals that cause overlaps.
Another viewpoint: The set of intervals must be a collection of non-overlapping intervals. So they must be able to be ordered without overlap. That means the intervals themselves should be non-overlapping pairwise. So if we take the union of intervals, they should be separated.
A useful concept: For a set of intervals, they are pairwise disjoint if and only if there is no "conflict" i.e., any two intervals intersect. This is equivalent to: the maximum number of intervals covering any point is <=1.
We can compute for each interval i, its "contribution" to overlaps. Removing an interval i reduces the count by 1 over its interval. So after removal, depth over each point is original depth minus indicator(i covers that point). We need that new depth <=1 everywhere.
Thus, condition for i: For all times t, depth(t) - (1 if t in [l_i, r_i) else 0) <= 1.
Equivalently: For all t, depth(t) <= 1 + (1 if t in [l_i, r_i) else 0). So depth(t) can be at most 2 if t is in i, but if t not in i, depth(t) must be <=1.
So we need to find intervals i such that:
Over all times t not in interval i, depth(t) <= 1.
Over times t in interval i, depth(t) <= 2. (Because after removal, depth <=1).
But careful: If an interval i is removed, then depth over i reduces by 1, so for times inside i, after removal depth = depth(t)-1 <=1 => depth(t) <=2. So yes.
Thus i is a candidate if:
The maximum depth over all times is at most 2? Actually, if depth(t) >= 3 for some t, then even after removing i, depth(t) would be at least 2 if i covers t, or still >=3 if i does not cover t. But we need <=1. So if there exists t such that depth(t) >=3, then no removal of a single interval can reduce depth to <=1 at t unless i covers t and depth(t) is exactly 3? Wait, condition: For t with depth(t) >=3, if i covers t then depth_after = depth(t)-1. For this to be <=1, we need depth(t)-1 <=1 => depth(t) <=2. So if depth(t) >=3, even if i covers t, depth_after >=2, which violates condition (needs <=1). So t with depth(t) >=3 cannot be fixed by removing any single interval. Thus for any solution to exist, the maximum depth must be at most 2. Also, for any t with depth(t)=2, the removal of i must cover t (so that depth_after becomes 1). Because if depth(t)=2 and i does not cover t, then after removal depth stays 2, which is >1. So for all points with depth=2, they must be contained in interval i. Moreover, for any point with depth=1, it's okay regardless.
Additionally, there cannot be any point with depth=2 that is not covered by i. Also, there cannot be any point with depth>2.
But also, after removal, intervals must be pairwise disjoint. Could there be a scenario where depth(t) <=2 everywhere, but after removal depth(t) <=1 but still intervals overlap? Actually if depth(t) <=1 everywhere, then intervals are pairwise disjoint, because if two intervals overlapped, there would be some t with depth >=2. So the condition is exactly that the depth after removal is <=1 everywhere.
Thus candidate i must cover all points where depth(t) = 2. i.e., the set of points with depth 2 must be a subset of the interval i. Since depth is defined over continuous time, we need that every t where depth(t) = 2 lies within [l_i, r_i). Also, we need that depth(t) never exceeds 2.
But careful: Could there be depth = 2 over a region, but that region may be covered by multiple intervals? The condition that all depth-2 points are inside i is necessary, but also we need that after removal, the remaining intervals (n-1 intervals) are pairwise disjoint. That means that for any two intervals j and k (both not i), they should not overlap. If depth(t)=2 is exactly due to overlapping of two intervals, removing one of them resolves that overlap. But if depth(t)=2 arises from two intervals that both overlap with i? Actually depth(t)=2 means exactly two intervals cover t. If those two intervals are j and k, then to reduce depth to 1, we must remove either j or k. So i must be one of those two. So i must be among the intervals that cover each depth-2 point. So i must be a common interval that covers all depth-2 points? Not exactly; depth-2 points may come from different pairs of intervals. For instance, suppose intervals A and B overlap in region X, and intervals A and C overlap in region Y, and B and C do not overlap. Then depth in X is 2 (A,B), depth in Y is 2 (A,C). To remove a single interval to eliminate all overlaps, we could remove A, which covers both X and Y. Then after removal, only B and C remain, which are non-overlapping if B and C don't overlap. That works. If we removed B, then region Y would still have overlap A and C? Wait, if we remove B, then at X depth after removal: originally depth 2 from A,B; removal of B -> depth 1 (only A). At Y: originally depth 2 from A,C; removal of B doesn't affect Y, so depth remains 2 (A,C), which is not allowed. So B is not a valid removal because the region Y remains overlapped. So indeed, the valid i must be an interval that covers all points where depth = 2. i must be present in every overlapping pair. That means that all overlaps (where depth=2) must involve i. In other words, the set of intervals that overlap with any other interval must all be a subset of intervals that intersect i? Let's formalize.
We need: For any two intervals j and k (j,k != i), they must not overlap. That is, if there exists any overlap between j and k, then at least one of j,k is i (since i is removed). So equivalently, any overlap (i.e., any pair of intervals that intersect) must include i. In other words, i is a vertex cover of the intersection graph (where vertices are intervals, edge if they intersect). But is vertex cover sufficient? Not exactly, because after removing i, the graph on remaining vertices must have no edges. That means all edges in the intersection graph must be incident to i. So i is a vertex that covers all edges: the graph's edges form a star centered at i (or i is a vertex cover of size 1). So the intersection graph must be such that there is a vertex i that is incident to all edges (i.e., all intersections involve i). Additionally, there must be no edges among other vertices. That's exactly the condition: For i to be valid, every pair of intervals (other than i) must be non-overlapping, and any interval overlapping with any other must overlap only with i. But also there could be multiple edges: maybe interval j overlaps with i, and interval k also overlaps with i, but j and k may also overlap? That would create an edge between j and k, which is not allowed unless i is also involved? Actually if j and k overlap, then they create an edge not incident to i (unless i also overlaps them but still edge j-k exists). So that would be a violation. So we require that the intersection graph is a star centered at i (including possibly isolated vertices). Alternatively, the set of intervals other than i are pairwise disjoint.
Now the depth condition we derived earlier: For all t with depth(t)=2, i must cover t. But is that equivalent? Let's examine.
Suppose the intersection graph is a star centered at i, and no other overlaps. Then depth(t) could be >2? Could there be a point where three intervals overlap? That would require at least three intervals covering t. If the graph is a star centered at i, it's possible that i overlaps with two intervals that also overlap with each other? That would cause depth 3? Actually if i overlaps with j and k, but j and k also overlap each other, then at a point where all three overlap, depth would be 3. But then the graph would have edges i-j, i-k, j-k, so not a star because j-k edge exists not incident to i? Actually i is incident to j-k edge? No, j-k edge is not incident to i; so it's not a star centered at i; it's a triangle. So that would be invalid because j and k overlap. So star property ensures no triple overlaps, but could there be depth=2 at some point from two intervals that are both i and j? That's fine. Could there be depth=2 from two intervals both not i? That would be j and k overlapping, which is not allowed. So depth=2 points must be exactly those where i and some other interval overlap (and no other intervals). So indeed, the set of depth=2 points is subset of i. But also, is it possible that depth=2 points are not all covered by i if there are multiple intervals overlapping with i? Actually any depth=2 point is covered by exactly two intervals. Since all edges involve i, those two intervals must be i and some j. So i is always one of them. So i covers all depth=2 points. That's necessary.
What about depth>2? That would involve more than two intervals, which would imply at least two intervals besides i overlapping at same time, which would create edges not incident to i? Actually if depth=3, that could be i, j, k covering t. Then j and k overlap (since they both cover t) even if they don't have edge? Actually if they both cover t, they intersect, so there is an edge j-k. That edge is not incident to i, so the graph would have edge j-k. So invalid. So if there is a solution with i, the original set cannot have depth>2 at any point. So indeed max depth <=2 is necessary.
Now, is the condition "max depth <=2 and all depth=2 points are covered by i" also sufficient? Let's test. Suppose max depth <=2. And for a given interval i, every point with depth=2 lies within i. Then after removing i, depth becomes <=1 everywhere. That implies no overlaps among remaining intervals. So yes, that condition is sufficient.
But careful: There is subtlety: If depth(t)=2 due to intervals j and k, but both j and k are not i, then t is not covered by i, contradicting condition. So condition ensures that every depth=2 point is covered by i, meaning i is one of the two intervals covering that point. However, could there be depth=2 point that is covered by i and some j, but also there might be another point where depth=2 is covered by i and some k, but j and k might overlap somewhere else not covered by i? That would create a depth=2 point not covered by i. Because if j and k overlap at some point, that point would have depth at least 2 from j and k; could be 2 if i not covering. That point would be depth=2 not covered by i, violating condition. So condition also prevents j and k from overlapping. So it's sufficient.
Thus we can compute depth function? But we need to check for each i whether it covers all depth=2 points. We can compute the union of all depth-2 points (i.e., the set of times where depth = 2). If that set is empty, then any i is valid? Actually if max depth <=1 initially (i.e., no overlaps at all), then the condition is trivially satisfied: after removing any interval, still no overlaps. So all i are valid. That's consistent with sample 1 where depth=2 points exist? Actually sample1 had intervals: [1,3), [3,10), [20,30). At time exactly 3? Since [1,3) ends at 3, and [3,10) starts at 3, they don't overlap. So depth is 1 everywhere. So depth=2 set empty. So all i valid.
If max depth >2, then no i can be valid. So answer is 0.
If max depth =2, we need to find intervals i that cover all points where depth =2.
But we must be careful: Depth function may be piecewise constant across intervals. The set of points with depth=2 is a union of intervals (possibly many). We need to test for each i if its interval [l_i, r_i) covers all those intervals (i.e., contains every point with depth=2). That is equivalent to: the whole depth-2 region is a subset of i. This can be checked by computing the overall interval that covers all depth-2 points? However, the depth-2 region might not be a single contiguous interval; it could be multiple disjoint intervals. For i to cover all depth-2 points, it must cover each subinterval. So we need to compute the union of all segments where depth=2, and check if i contains that union.
We can compute depth function using sweep line over sorted endpoints. Since n=5000, we can easily compute the intervals where depth=2 (and also >2). But we need to also consider boundary conditions: intervals are half-open [l, r). So we must be consistent.
Alternatively, we can reason about pairwise intersections. Since n is only 5000, we could compute intersection graph edges and then check for each vertex if it's a vertex cover of size 1. That is, count number of edges. If edges > 0, check if there exists a vertex that is incident to all edges. If so, and also check that there is no edge among other vertices (which is automatically satisfied if that vertex is incident to all edges because any edge would be incident to it). But careful: Could there be an edge that is not incident to i but we don't have any edges? Actually if a vertex is incident to all edges, then any edge has that vertex as one endpoint. So no edge exists between two other vertices. So that condition is sufficient. Also we must ensure that there are no edges besides those incident to i. That's covered. But also need to consider that there might be overlapping intervals that do not create an edge? Wait, overlapping intervals always create an edge in intersection graph. So if we have an edge set, representing all pairs of intersecting intervals. But there is a nuance: Could there be overlapping that results in depth>2 but still only edges incident to i? For depth=3, there would be three intervals all mutually overlapping? Actually if three intervals all overlap at some point, then the intersection graph among them would have edges between each pair. If one vertex i is incident to all edges, then edges (j,k) would exist but would not be incident to i. So to have all edges incident to i, the graph must be a star, which implies max degree? Actually star means no edges between leaves. That means no two leaves overlap. So depth cannot exceed 2 because if two leaves overlapped, they'd create an edge not incident to i, and also at overlapping point they'd both cover along with i? Actually if i overlaps with j and with k, but j and k also overlap, then at points where j and k overlap, if i also covers that region, depth=3; if i does not cover, depth=2 from j and k. In either case, there is an edge j-k not incident to i, so i would not be incident to all edges. So star condition ensures max depth <=2 and depth=2 points are only those where i and a leaf overlap.
Thus, we can simply compute all intersecting pairs and then find i such that every intersecting pair includes i. Also need to check that there is no intersecting pair among others. But if every intersecting pair includes i, then automatically there is none among others. So condition: For all pairs (j,k) with j<k, if intervals j and k intersect (according to half-open rule), then either j=i or k=i. This means that the set of intersecting pairs is a subset of pairs where one is i. So i is a "hub" for all intersections.
But wait: what about if there are no intersecting pairs at all (i.e., all intervals disjoint). Then condition "for all intersecting pairs, either j=i or k=i" is vacuously true for any i. So all i are valid. That matches.
If there are intersecting pairs, we need i to be the common element across all those pairs. That is, all intersecting pairs share the same interval i. So there is at most one such i? Could there be two? Suppose intervals A and B intersect, and also A and C intersect, but B and C do not intersect. Then intersecting pairs are (A,B) and (A,C). Then i could be A. Could i be B? Check: For pair (A,B), i=B would include B? It would require either j=i or k=i. For (A,B), if i=B, then condition satisfied (since B is one of them). For (A,C), if i=B, then neither j nor k is B, so condition fails. So B not valid. Similarly C not valid. So only A. Could there be a case where intersecting pairs are (A,B) and (B,C) and (A,C) maybe? Then no single i covers all because any i would miss one edge. So no solution. Could there be two possible i? Suppose only one intersecting pair (A,B). Then both A and B satisfy condition? For i=A, pair (A,B) includes A, so ok. For i=B, also includes B, ok. So both A and B could be valid? But we must also check that after removal, the remaining intervals are pairwise disjoint. Let's test: intervals: A and B intersect; all other intervals are disjoint from each other and from A and B? If only intersecting pair is (A,B), then removing either A or B leaves no intersections. So both A and B are valid. Does this satisfy depth condition? max depth = 2 at the overlapping region of A and B. For i=A, does A cover all depth-2 points? The depth-2 region is the intersection of A and B. Since A covers that region (obviously, as it's part of A). So yes. Similarly for i=B. So both are valid. So it's possible to have multiple valid indices. So we need to output all.
Now, what about scenario where there are multiple intersecting pairs but all share a common interval i? Then i is valid. Could there also be another interval j that also appears in all intersecting pairs? That would mean all intersecting pairs include both i and j, which is impossible unless there is only one pair? Because if there is a pair (i,j), that includes both. But if there is another pair (i,k) with k not j, then j does not appear in (i,k). So j wouldn't be in all. So at most one interval can be the common intersection hub if there are at least two distinct intersecting pairs with different other intervals. However, if there is exactly one intersecting pair, both endpoints are common to all pairs (since only one pair), so both are valid. So indeed, the condition reduces to:
Compute all intersecting pairs (i.e., edges in the intersection graph).
If there are zero edges, all indices are valid.
Else, let E be the set of edges. We need to find vertices that appear in every edge. That is, the intersection of all edge-sets? Each edge is a set of two vertices. For a vertex v to be in every edge, it must be that for every edge {a,b}, v ∈ {a,b}. So the set of common vertices = ∩_{edges} {a,b} (the intersection over edges of the two-element set). If there are at least 2 edges, the intersection may be empty or have exactly one vertex. For example, edges {1,2} and {1,3}: intersection = {1}. For edges {1,2} and {2,3}: intersection = {2}? Intersection of {1,2} and {2,3} is {2}. So yes, can be one. For edges {1,2} and {3,4}: intersection empty. For edges {1,2} only: intersection = {1,2} (both). So if there are >1 edges, the intersection must be a single vertex for there to be a valid one (since two distinct vertices cannot both be in every edge unless edges are only the pair containing both, but then edges would be only one? Actually if edges are {1,2} and {1,2} duplicates? Not possible. So if >1 edges, common vertices set can be at most one). If the intersection is non-empty, then those vertices are candidates.
But is intersection being non-empty sufficient? Let's test with edges {1,2}, {1,3}. Intersection = {1}. Remove 1: remaining intervals: 2 and 3. Are 2 and 3 guaranteed to be non-intersecting? The edges we have only indicate intersections between 1-2 and 1-3. There is no edge between 2 and 3. But does that guarantee 2 and 3 are disjoint? Intersection graph only records if they intersect. So if we only computed edges for pairs that intersect, we have not computed pairs that do not intersect. If there is no edge between 2 and 3, they are non-intersecting. So removal of 1 leaves no edges. So condition holds. However, what about points where depth>2? Could there be a triple overlap without pairwise intersections? Actually if three intervals overlap at a point, all three pairs intersect. So that would produce edges between each pair. So if we only have edges 1-2 and 1-3, but no edge 2-3, then there cannot be a point where 2 and 3 overlap, because that would create edge 2-3. So fine. So the condition that all edges involve i ensures that after removal, no edges remain. So it's sufficient.
But what about the scenario where depth=2 region is covered by i, but there might be some overlapping that is not captured by pairwise intersections? Overlapping means there exists a time t covered by two intervals, so that pair intersects. So it's captured. So the edge-based condition is equivalent.
Thus we can solve by computing all intersecting pairs and then analyzing. n=5000, so number of pairs is up to ~12.5 million, which might be borderline but possibly okay in C++ with optimization, but in Python? n=5000 -> 12.5 million comparisons of pairs. Could be okay if done efficiently (12.5M is not huge in Python, but could be slow if not optimized? Typically 10^7 operations in Python is okay within a second? Might be borderline but with simple integer comparisons and early exit? But we need to compute all pairs: O(n^2) = 25e6 half? Actually n=5000, pairs = n*(n-1)/2 ~ 12.5e6. Doing 12.5 million comparisons might be okay in PyPy if efficient. But we also need to store edges? We don't need to store all edges; we just need to determine common vertices across edges. We can process on the fly:
If there are zero edges, all indices are valid.
Otherwise, we need to find if there exists a vertex that is in every edge.
One approach: For each vertex, we could check if it's a candidate by verifying that it intersects with all others? Not exactly.
We can compute the set of vertices that are involved in edges. Also compute the intersection of all edge-sets.
Initialize common set as None. For each pair (i,j) that intersect:
If common set is None, set common = {i,j}
Else, set common = common ∩ {i,j}
If common becomes empty, we can break early (since no candidate). However, we might still need to continue to detect if there is any triple overlap or depth>2? Actually even if common empty, no single vertex can be in all edges, so answer should be 0. But we must also check for max depth>2? But if common empty, maybe still some vertex works? Wait, suppose edges are {1,2} and {2,3}. Intersection = {2} which is not empty, so candidate 2. So empty common means no vertex in all edges, so no solution. But could there be a case where common non-empty but still invalid due to depth>2? Consider edges: {1,2}, {1,3}, {2,3}. Intersection of these three sets = {} (since {1,2} ∩ {1,3} = {1}, then ∩ {2,3} = {}). So common empty -> no candidate. So no solution. That matches expectation: triangle of intersections can't be fixed by removing one. So the edge intersection method seems sufficient.
But wait, consider a scenario with intervals that cause depth=3 at some point but maybe there is a vertex that is in all edges? Example: intervals: A=[1,5], B=[2,6], C=[3,7]. Pairwise intersections: all pairs intersect: (A,B), (A,C), (B,C). Intersection of all edge-sets is empty (since no single vertex in all pairs). So no candidate. Indeed, removing any one leaves two intervals that still intersect. So answer 0. So that's correct.
But consider scenario: intervals: A=[1,4], B=[2,5], C=[3,6], but suppose C does not intersect A? Actually if A and C do not intersect (but B intersects both), then edges: (A,B) and (B,C). Intersection = {B}. That yields candidate B. Check depth: A and B overlap region [2,4]; B and C overlap region [3,5]; But A and C may not overlap (if A ends at 4 and C starts at 3? Actually they might overlap if A=[1,4] and C=[3,6], they overlap [3,4]. So they would intersect. So to have edges only (A,B) and (B,C) we need A and C disjoint. For instance, A=[1,3], B=[2,4], C=[5,7]? Then B and C not intersect. Not that. Let's construct: A=[1,4], B=[3,6], C=[5,8]? Then A and B intersect? [3,4] overlap yes; B and C intersect? [5,6] overlap yes; A and C? A ends 4, C starts 5 -> no intersect (if half-open [4,5) boundary not overlapping). So edges: (A,B) and (B,C). Intersection = {B}. So candidate B. After removing B, remaining A and C are disjoint. So works. Depth: max depth =? At [3,4) depth 2 (A,B). At [5,6) depth 2 (B,C). Also maybe B alone elsewhere depth1. So depth never exceeds 2, and all depth-2 points are within B? Actually first depth-2 region [3,4) is within B (yes). Second [5,6) also within B (yes). So condition satisfied. So candidate works.
But what about scenario where depth=2 regions are within multiple intervals, but one interval covers all? That is captured by intersection of edges.
Thus the problem reduces to: find all intervals i such that every intersecting pair involves i. This can be computed by:
For each i, we could count the total number of intersecting pairs and the number of intersecting pairs that involve i. If total pairs >0 and for i, the number of pairs that involve i equals total pairs, then i is a candidate. However, careful: It's possible that there is a pair that does not involve i but that pair does not intersect? Actually total pairs meaning only intersecting pairs. So if we count total intersecting pairs, then i is candidate if every intersecting pair includes i, i.e., the count of intersecting pairs that include i equals total intersecting pairs. And also, there should be no intersecting pair that doesn't include i, so this condition is sufficient. But is it necessary? Yes.
But we also need to consider if there are any intersecting pairs at all. If zero, all i are candidates.
So we can compute for each i, the number of intervals it intersects (i.e., degree in intersection graph). Sum of degrees / 2 = total intersecting pairs. But degree count includes each intersecting pair once. So total_edges = sum(degree_i)/2. Then i is a candidate if degree_i == total_edges? Wait, if i is incident to all edges, then each edge includes i, so each edge contributes 1 to degree_i. So degree_i should equal total number of edges (since each edge contributes exactly 1 to degree_i). However, if there are multiple edges, degree_i = number of edges because each edge is counted once in degree_i? Actually each edge (i,j) contributes 1 to degree_i and 1 to degree_j. If i is in every edge, then each edge contributes 1 to degree_i. So degree_i = total_edges. But also i might have degree larger than total_edges? Not possible because degree_i counts edges incident to i. If i is in all edges, then indeed degree_i = total_edges. However, if there is only one edge (i,j), then total_edges = 1, degree_i = 1, degree_j = 1, so both satisfy degree_i == total_edges. So that condition would mark both i and j as candidates. Good.
If total_edges = 0, then degree_i = 0 for all i. But degree_i == total_edges (0) holds for all i. That would indicate all are candidates, which is correct. So we could use the condition: i is candidate if degree_i == total_edges.
But is there any scenario where degree_i == total_edges but i is not a valid candidate? Let's think: Suppose there are edges: (1,2) and (1,3). Then total_edges = 2. degree_1 = 2, degree_2 = 1, degree_3 = 1. So only i=1 satisfies degree_i == total_edges. That's correct.
Now suppose there are edges: (1,2), (2,3), (1,3). Then total_edges = 3. degree_1 = 2, degree_2 = 2, degree_3 = 2. None have degree == 3, so none are candidates. Good.
Suppose there is a scenario where there is an edge (1,2) and also (1,2) duplicate? Not possible. So seems fine.
But wait, could there be a scenario where there is an edge (1,2) and also (1,2) counted twice? No.
But we must ensure that the intersection condition is exactly captured by degree_i == total_edges. However, consider scenario: intervals 1 and 2 intersect, and also 1 and 3 intersect, and additionally 2 and 3 intersect? That we already considered: degree_1=2, total=3, so not equal, so not candidate, correct.
Now consider scenario where there is an edge (1,2) and (1,2) only one edge? Already fine.
Now consider scenario where there are no edges, total_edges = 0, all degree_i =0, so condition holds for all, correct.
Thus we can compute degree_i for each i (number of other intervals that intersect it) and total_edges = sum degree_i / 2. Then for each i, if degree_i == total_edges, it's a candidate.
But is this condition sufficient even if there are overlapping intervals that cause depth>2? Let's test: Suppose intervals 1,2,3 all overlap at a common region. Then we have edges (1,2),(1,3),(2,3): total_edges = 3, degree_1=2,2,2 -> none equal 3, so no candidate. Good.
Now suppose intervals 1,2,3 but only 1 overlaps with 2 and 3, but 2 and 3 also overlap? That would create edge (2,3) which adds to total and increases degree of 2 and 3, making degree_1=2, total would be 3, degree_1=2 <3. So no candidate. So condition fails.
But what about a scenario where there is an interval i that overlaps with many others, but some others also overlap among themselves without i? That would increase total_edges beyond degree_i, so condition fails.
Thus condition seems both necessary and sufficient.
But we need to be careful: The definition of intersection must be consistent: intervals [l_i, r_i) and [l_j, r_j) intersect if and only if max(l_i, l_j) < min(r_i, r_j). Because they must share some positive time; if one ends exactly when another starts, they do not intersect. So we can implement overlap condition as: not (r_i <= l_j or r_j <= l_i) but using strict less for the opposite? Actually condition for disjoint (non-intersect) is: r_i <= l_j or r_j <= l_i. Since intervals are half-open, if r_i == l_j, then the point l_j is not covered by i because i covers up to but not including r_i? In half-open [l_i, r_i), the time r_i is not included. So intervals are disjoint if r_i <= l_j or r_j <= l_i. That's correct. Intersection if r_i > l_j and r_j > l_i. Note that if r_i == l_j, then not r_i > l_j (since ==), so no intersection. So condition: intervals intersect iff l_i < r_j and l_j < r_i. Equivalent to max(l_i, l_j) < min(r_i, r_j).
We'll use that.
Now algorithm:
Input n, intervals list.
Initialize degree = [0]*n.
total_edges = 0 (or compute later).
For i from 0 to n-1:
for j from i+1 to n-1:
if intervals i and j intersect:
degree[i] += 1
degree[j] += 1
After loop, total_edges = sum(degree) // 2.
Then candidate indices = [i+1 for i in range(n) if degree[i] == total_edges]
But we must be careful: if total_edges == 0, then condition holds for all i. That's fine.
Time complexity: O(n^2) with n up to 5000 => ~12.5M iterations. In Python, 12.5M simple comparisons should be okay (< 0.5 seconds maybe). But we need to be mindful of input and output. Using PyPy it should pass. However, we need to ensure that we don't do heavy operations inside loop. Just comparing integers and increment.
But is there any nuance? Let's test on given examples:
Example 1:
n=3
(3,10), (20,30), (1,3)
Check pairs:
(3,10) vs (20,30): 10 <= 20? Actually r1=10, l2=20 => disjoint because r1 <= l2? 10 <=20 true, so no intersect.
(3,10) vs (1,3): l1=3, r1=10; l2=1, r2=3. Condition intersect: max(3,1)=3 < min(10,3)=3? 3<3 false, so no intersect. (Because r2=3 <= l1? 3<=3? Since r2=3, l1=3, r2 <= l1 -> 3 <= 3 true, so disjoint). So no intersect.
(20,30) vs (1,3): obviously disjoint.
So degree all 0, total_edges=0, all degree==0, candidates all indices => output 1 2 3.
Pairs:
1-2: 10 <=20 -> disjoint.
1-3: 10>1? Check intersect: l1=3,r1=10; l3=1,r3=3; max(3,1)=3 < min(10,3)=3? false => disjoint (since r3=3 <= l1=3 -> disjoint)
1-4: [3,10) vs [1,39): intersect? 3<39? and 1<10? Yes => intersect. So degree[1]++, degree[4]++.
2-3: [20,30) vs [1,3): disjoint.
2-4: [20,30) vs [1,39): intersect? 20<39 and 1<30 -> yes. degree[2]++, degree[4]++.
3-4: [1,3) vs [1,39): intersect? max(1,1)=1 < min(3,39)=3? 1<3 true => intersect. degree[3]++, degree[4]++.
So degrees: deg1=1, deg2=1, deg3=1, deg4=3. total_edges = (1+1+1+3)/2 = 6/2=3. Check degree_i == total_edges? Only deg4 == 3, so only index 4. Output 1 and 4. Matches.
Example 3:
3
1 5
2 6
3 7
All pairs intersect:
1-2: intersect (1<6 and 2<5) yes. deg1,deg2.
1-3: intersect (1<7 and 3<5) yes. deg1,deg3.
2-3: intersect (2<7 and 3<6) yes. deg2,deg3.
Degrees: deg1=2, deg2=2, deg3=2. total_edges= (2+2+2)/2=3. No degree equals 3, so output 0. Matches.
Thus the simple degree condition works for these examples.
But is it always correct? Let's consider edge cases.
Potential pitfalls:
If there are multiple intervals that are identical? For instance, two intervals exactly the same [1,5], and a third [6,10] disjoint. Pairs: the two identical intervals intersect (they share all points). So edges: one edge between the two identical intervals. Degrees: each of those two gets degree 1, the third gets 0. total_edges = 1. Candidates: those with degree=1: both of the overlapping intervals. After removing one, the remaining intervals are [1,5] and [6,10], which are disjoint? Wait, the remaining would be one of the identical intervals and the disjoint one: they are disjoint? [1,5] and [6,10] are disjoint if 5<=6? Actually r=5, l=6 => 5<=6, so disjoint. So both are valid. So output both, correct.
If there are three intervals where two intersect and third intersects one but not the other? That's the star case: intervals A and B intersect, A and C intersect, B and C disjoint. Edges: (A,B), (A,C). Degrees: A=2, B=1, C=1. total_edges=2. Only A has degree=2 => only A valid. That seems correct: removing A leaves B and C which are disjoint. Removing B leaves A and C which intersect (since A and C intersect), so invalid. Similarly C invalid.
What if there is only one edge (A,B) but also another interval C that is disjoint from both? Then degrees: A=1, B=1, C=0. total_edges=1. Both A and B have degree=1 => both valid. Removing A leaves B and C, which are disjoint? B and C are disjoint? Yes by assumption. So valid. Good.
What if there is an edge (A,B) and also edge (B,C) but A and C disjoint? Then edges: (A,B) and (B,C). Degrees: A=1, B=2, C=1. total_edges=2. Only B has degree=2 => only B valid. Check: remove B leaves A and C, which are disjoint -> valid. Remove A leaves B and C: B and C intersect (since edge B,C) => invalid. Remove C leaves A and B: they intersect => invalid. So B valid. Good.
What if there are two edges that are (A,B) and (A,C) and (A,D) etc. Star with center A. Then A degree = number of edges, total_edges = number of edges. So A valid. Others not.
What if there are edges but all edges involve two specific intervals? For instance, only edges are (A,B) and (A,B) duplicate? Not possible. Or edges (A,B) and (A,B) can't. So not.
Now, is there any scenario where degree_i == total_edges but i is not valid because after removal there might still be some overlap due to intervals that are not directly intersecting but still overlapping via multiple intervals? Actually overlap is binary; if two intervals don't intersect directly, they can't overlap. So if after removal there is no pair of intervals that intersect, then all is good. And the condition degree_i == total_edges ensures that every intersecting pair involves i. Since we remove i, all intersecting pairs are eliminated. So there are no intersecting pairs left. So condition is sufficient.
But wait: Could there be a situation where after removing i, there exists a pair of intervals that do not intersect in the original set but become intersecting because we remove i? That's impossible. Removal cannot create new intersections.
Thus condition is correct.
But is it possible that there is an intersecting pair that is not detected because of the half-open interpretation but actual problem statement uses inclusive-exclusive? The problem says: "If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect." So we interpret as intervals [l, r) or (l, r]. So our condition for intersection using strict inequality as above is correct: intersect if max(l_i, l_j) < min(r_i, r_j). Or equivalently, if not (r_i <= l_j or r_j <= l_i). Using <= for disjoint.
Now we must ensure we compute degree correctly with that condition.
Now consider edge case: intervals like [1,2], [2,3]. They are disjoint because first ends at 2, second starts at 2. So no intersection. That matches problem.
Now think about potential pitfalls: If there are many intervals and many intersections, O(n^2) might be borderline but n=5000, 12.5M is okay. In Python, with simple operations, it should be fine under 2 secs? Let's approximate: 12.5e6 comparisons, each with a few integer operations, maybe 0.1-0.2 sec in PyPy? Actually Python can do about 50 million simple operations per second? Not sure; in PyPy maybe 10-20 million per second. So 12.5M should be fine. We'll also need to read input and output.
But caution: The input size is up to 5000 lines, small.
Thus solution: O(n^2) pairwise check, compute degrees, total edges, then filter.
But we must be careful: In some cases, the overlapping condition might be more subtle: The intervals are given as integers and we treat them as continuous. Our condition works.
Now, confirm with more tricky cases:
Case: n=2, intervals intersect. degree each =1, total_edges=1. Both degree==total => both candidates. Removing either leaves single interval, obviously no intersections. So output both indices. That's correct.
Case: n=2, intervals don't intersect. degree=0, total=0 => both candidates. That's correct: remove either, remaining one interval, no intersections.
Case: n=5000 with all intervals disjoint: O(n^2) will check all pairs but early detection? No, we still need to compute degrees, but all pairs are disjoint. So 12.5M checks with condition that is false for all. That's okay.
But we can perhaps optimize by sorting intervals and then checking only nearby intervals? Because O(n^2) with n=5000 is fine. So no need.
Now double-check that degree_i == total_edges is indeed necessary and sufficient. Sufficiency argued. Necessity: If i is valid, then all intersecting pairs involve i. So degree_i = total_edges. So yes.
But there is a nuance: What if there are intersecting pairs but some involve i and some involve j but after removing i, maybe there is still an intersecting pair? Actually if i valid, then after removal there are no intersecting pairs, meaning originally any intersecting pair must have i as one of its endpoints. So indeed all edges incident to i. So degree_i = total_edges. So condition holds.
Read n
intervals = []
for i in range(n):
l, r = map(int, input().split())
intervals.append((l, r))
degree = [0]*n
for i in range(n):
li, ri = intervals[i]
for j in range(i+1, n):
lj, rj = intervals[j]
if max(li, lj) < min(ri, rj):
degree[i] += 1
degree[j] += 1
total_edges = sum(degree)//2
candidates = [i+1 for i in range(n) if degree[i] == total_edges]
print(len(candidates))
if candidates:
print(' '.join(map(str, candidates)))
else:
print() # but output second line always? In examples, they printed second line even if k=0? In sample 3, output "0" and then second line? Actually sample 3 output:
Output
0
There is no second line. In statement: "Output integer k — amount of ways ... In the second line output k numbers — indexes of groups" So if k=0, we output just the first line with 0, and presumably no second line. In sample 3, it's just "0". So we can handle accordingly: print(k); if k>0: print the numbers.
Now test with given examples.
Edge Cases:
n=1: single interval. No pairs, degree[0]=0, total_edges=0, candidate condition true, so k=1, output index 1. Removing the only group yields empty set, which trivially has no intersections. That seems valid? Problem: "cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect." If there is only one group, after removing it, there are zero groups, so vacuously no two intersect. So yes, it's a valid way. So output 1 and "1". That makes sense.
n=0? Not allowed, n>=1.
Now, any potential issues: The degree counting method works as long as we count each intersecting pair exactly once. But need to ensure we treat intervals that are exactly same? They intersect (since max(l,l)=l < min(r,r)=r => true). So counted.
Now, one more nuance: Could there be intervals that are "nested"? For example, [1,10] and [2,3] intersect. That's fine.
Now, is there any scenario where degree_i == total_edges but after removal there is still some overlapping because three intervals overlapped at a point but two of them didn't pairwise intersect? That's impossible: if three intervals all cover a point t, then each pair of them also covers t, so they pairwise intersect. So edges exist. So if there is a point covered by three intervals, there will be three edges. In that case, any vertex i could have degree_i <= total_edges? Actually total_edges would be at least 3, degree_i at most 2 (since it can be adjacent to at most two others in a triangle? In triangle, each vertex degree=2, total_edges=3, so degree_i != total_edges. So condition fails.
Thus condition robust.
Now, consider scenario where there is an intersecting pair (i,j) and also (i,k) but j and k also intersect at a point that is not covered by i? If j and k intersect, then there is edge (j,k). Then degree_i would be 2, total_edges would be 3 (if only these three edges). So degree_i != total_edges. So condition fails. But what if j and k intersect but also i covers that same region? Then still edge (j,k) exists. So degree_i=2, total_edges=3, fails. So condition fails. Good.
Now, could there be a situation where there is an intersecting pair (i,j) and also (i,k), but j and k intersect exactly at boundary points that are not considered intersecting because of half-open? Suppose j=[1,3), k=[3,5)? They don't intersect. So no edge. So condition holds for i.
Thus algorithm seems correct.
But wait, are we missing the possibility that after removal, the remaining intervals might still have "intersections" due to chain of intervals? No, intersections are pairwise.
Now, the problem statement says: "It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect." So our interpretation matches.
Now, given that n can be up to 5000, the O(n^2) method is acceptable.
But we must ensure that we use fast I/O. Use sys.stdin.read() to parse all quickly.
Implementation details:
We'll read all ints via sys.stdin.buffer.read().split().
Then process.
Pseudo:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
intervals = []
for _ in range(n):
l = int(next(it)); r = int(next(it))
intervals.append((l, r))
degree = [0]*n
for i in range(n):
li, ri = intervals[i]
for j in range(i+1, n):
lj, rj = intervals[j]
if li < rj and lj < ri: # equivalent to max(li,lj) < min(ri,rj)
degree[i] += 1
degree[j] += 1
total = sum(degree)//2
cand = [str(i+1) for i in range(n) if degree[i] == total]
out = []
out.append(str(len(cand)))
if cand:
out.append(' '.join(cand))
sys.stdout.write('\n'.join(out))
if name == 'main':
main()
Test with examples.
Now, verify the condition li < rj and lj < ri is correct for half-open intervals intersection. Indeed, intervals intersect if they share any point. For half-open [l_i, r_i) and [l_j, r_j), the condition is l_i < r_j and l_j < r_i. Because if l_i < r_j then there is some point greater than l_i and less than r_j; also need l_j < r_i to ensure overlap. Actually the condition is that the intervals overlap if the start of one is less than the end of the other and vice versa. More precisely, the intersection is non-empty if max(l_i, l_j) < min(r_i, r_j). Equivalent to l_i < r_j and l_j < r_i. Let's test: [1,3) and [3,5): l1=1<r2=5 true, l2=3<r1=3 false (3<3 false). So condition false -> no intersection. Good. [1,3) and [2,4): l1=1<4 true, l2=2<3 true -> true. Good. So we can use that.
Now, about integer overflow? Not.
Now, does the algorithm need to consider that the depth might be >2 even if graph edges are all incident to one vertex? Could there be depth 3 where the three intervals overlapping all share a common point but one of them is i? For depth 3, we need three intervals covering a point. If i is one of them, then the other two also cover that point, so they intersect each other at that point, creating an edge between them. So that edge is not incident to i. Therefore, i would not be incident to all edges. So condition would fail. So our condition automatically excludes depth >2. So we don't need to compute depth separately.
Thus solution is simple and robust.
Now, we must consider potential pitfalls: The intervals could be large values up to 1e6, but no matter.
Now, is it possible that there is a vertex i such that degree_i == total_edges but i not valid because there is a point with depth >2 but that point is covered by i and the other two intervals but those two intervals do not intersect? Wait, if three intervals all cover a point t, then by definition each pair of intervals covers t, so they intersect. So there would be edges between each pair. So if i, j, k all cover t, then edges (i,j), (i,k), (j,k) exist. So total_edges >= 3, degree_i would be at least 2 (since edges (i,j) and (i,k) contribute, but also if there are only those three intervals, degree_i = 2, total_edges = 3, condition fails. So i would not be candidate. So it's fine.
Now, could there be a scenario where depth=2 everywhere but the depth=2 region is not entirely covered by a single interval? For example, intervals: A=[1,5], B=[4,8], C=[7,10]. So A and B overlap on [4,5); B and C overlap on [7,8); A and C do not overlap. Edges: (A,B) and (B,C). So degree_A=1, degree_B=2, degree_C=1, total_edges=2. Only B has degree==2. So candidate B. Indeed, removing B leaves A and C disjoint. So condition holds.
Now, suppose we have intervals: A=[1,4], B=[3,6], C=[5,8]. A and B overlap on [3,4); B and C overlap on [5,6); A and C disjoint? A ends 4, C starts 5, so disjoint. So same pattern. B valid.
Now, suppose intervals: A=[1,5], B=[2,4], C=[3,6]. Edges: A-B (overlap), A-C (overlap [3,5]), B-C (overlap [3,4]). So triangle, no candidate. So correct.
Now, consider intervals: A=[1,5], B=[2,3], C=[4,6]. A-B overlap, A-C overlap? A=[1,5] and C=[4,6] overlap on [4,5) => yes. B and C? B=[2,3] and C=[4,6] disjoint because 3 <=4? Actually B ends at 3, C starts at 4, disjoint. So edges: (A,B), (A,C). That's a star centered at A. So A valid. Good.
Now, consider intervals: A=[1,5], B=[2,6], C=[3,7] but B and C overlap? Obviously yes, triangle. So no candidate.
Now, consider intervals: A=[1,5], B=[6,10], C=[5,6]. A and C: A ends 5, C starts 5, if half-open, A=[1,5), C=[5,6) => disjoint. B and C: C ends 6, B starts 6 => disjoint. So no edges, all valid. So condition works.
Now, consider intervals: A=[1,3], B=[3,5], C=[2,4]. Then A and B disjoint; A and C overlap? A=[1,3), C=[2,4): overlap [2,3) => yes. B and C: B=[3,5), C=[2,4): overlap? max(3,2)=3 < min(5,4)=4 => 3<4 true => overlap (since 3 is included? Actually B starts at 3, C ends at 4, B is [3,5). At t=3, B includes 3? Yes, half-open includes start, excludes end. So B includes 3; C includes 3? C includes 3? [2,4) includes 3. So they share t=3? But condition max(3,2)=3 < min(5,4)=4, true, so intersect. So edges: (A,C) and (B,C). So degrees: A=1, B=1, C=2. total=2. Only C has degree==2. So candidate C. Remove C leaves A and B, which are disjoint (A ends at 3, B starts at 3) -> disjoint. So valid. Good.
Now, consider intervals: A=[1,3], B=[2,4], C=[3,5]. A and B overlap; B and C overlap? B=[2,4), C=[3,5): overlap [3,4)? B includes 3? yes; C includes 3? yes; so overlap; A and C? A=[1,3), C=[3,5): disjoint. So edges: (A,B), (B,C). So star centered at B? Actually edges: (A,B) and (B,C). So B degree=2, total=2. B valid. Removing B leaves A and C, which are disjoint. Good.
Now, consider intervals where there are multiple disjoint overlapping clusters? For example, two separate pairs that do not intersect each other: A and B intersect, C and D intersect, but no other intersections. Then edges: (A,B) and (C,D). total_edges=2. Degrees: A=1, B=1, C=1, D=1. No vertex has degree=2. So no candidate. Indeed, removing any single interval will still leave at least one intersecting pair (the other pair). So answer 0. Good.
Now, consider clusters: one pair (A,B) and one triple star (C,D,E where C is center). But overall edges include edges from both clusters. The total_edges = 1 + number of edges in star. For candidate i to have degree == total, i would need to be incident to all edges across clusters. If i is the center C, it would be incident to edges within its star but not to (A,B). So degree_C < total. If i is A, it would be incident to (A,B) but not to star edges. So no candidate. So answer 0, which is correct because if we remove A, the star cluster still has intersections; if remove C, the (A,B) pair remains intersecting.
Thus condition correctly identifies only when all intersections are concentrated on a single interval.
Now, we should also consider if there are zero intersecting pairs, then all are candidates. That's consistent.
Now, is there any scenario where there is exactly one intersecting pair, but one of the intervals also intersects a third interval? That would create at least two edges, not one. So not.
Thus algorithm is good.
But is it possible that some intervals may have overlapping that are not captured by pairwise intersection due to the half-open definition but still cause depth>2? No.
Now, we need to think about potential pitfalls due to integer boundaries: intervals are given as integers. Our condition using < and > works.
Now, implement.
But we need to consider performance: nested loops with Python might be slower if we use Python's built-in functions not. But 12.5M iterations is okay. However, we can try to micro-optimize: pre-store l and r in separate arrays for faster access, use local variables in loops, avoid function calls.
We'll do:
l = [0]*n
r = [0]*n
for i in range(n):
l[i], r[i] = map(int, ...)
degree = [0]*n
for i in range(n):
li = l[i]; ri = r[i]
for j in range(i+1, n):
if li < r[j] and l[j] < ri:
degree[i] += 1
degree[j] += 1
That should be efficient.
Alternatively, we could sort intervals and then use sweepline to compute degrees more efficiently, but not necessary.
Now, check potential issue: The sum of degrees might be odd? It's always even because each edge contributes 2. So integer division fine.
Now, output format: if k>0, second line numbers separated by spaces, and trailing space? In examples they have trailing space after the numbers? Actually sample 1 output:
3
1 2 3
There is a space after 3. Usually it's okay if we print with join, no trailing space unless we add one. We'll print join.
Now, test with sample2: Output "1" then "4". Our join would be "4". Good.
Now, edge case: k=0: just print "0". No second line.
Now, correctness: Did we consider that the intervals are given as (li, ri) where li<ri, so not degenerate.
Now, confirm with sample 2 computed above: matches.
Now, consider case n=5000 all intervals same: [1,2]. Then each pair intersects. Number of edges = n*(n-1)/2 = ~12.5e6. Then total_edges huge. Degrees: each degree = n-1 = 4999. So degree_i = 4999, total_edges = n*(n-1)/2 ≈ 12.5e6, so degree_i != total_edges. So no candidate, answer 0. That seems correct: If all intervals are identical, removing one still leaves many intersecting pairs. So output 0.
Now, case n=5000 with all intervals [i, i+1) for i=1..5000? They are disjoint (adjacent but not overlapping because [1,2) and [2,3) are disjoint). So no edges, all candidates. That would produce a list of 5000 indices. Output would be huge but allowed (n up to 5000). That's fine.
Now, check time: For all disjoint intervals, our nested loop still does O(n^2) checks, each check false, but 12.5M checks still fine.
But we might want to exit early if we find that there are >1 vertices with degree high? But we still need to compute degrees to know total. But we can compute degrees and total edges in one pass. That's fine.
Now, potential problem: Memory for reading? Not, 5000*2 ints.
Now, confirm that we haven't misinterpreted intersection condition. Let's re-read problem statement: "If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect." This implies that if one ends exactly when another starts, they are not intersecting. So our condition is correct.
Now, think about integer boundaries: If we have intervals [1,2] and [2,3] they are disjoint.
Now, double-check sample 1: They had intervals: (3,10) (20,30) (1,3). Our code would treat them as disjoint, as we saw. So good.
Now, consider case where l and r can be up to 10^6. No problem.
Thus the solution is straightforward.
But is there any hidden trap? The condition degree_i == total_edges might be insufficient if there are multiple intervals that are identical? Actually if there are two identical intervals (both overlapping each other) and a third that overlaps with both? For example: intervals: A=[1,5], B=[1,5], C=[2,6]. Pairwise intersections: A-B intersect, A-C intersect, B-C intersect. So all three edges, triangle, degrees: each 2 (A: with B and C; similarly), total=3. No degree==3. So no candidate. But is there a valid removal? If we remove A, we have B and C, which intersect (since identical intervals B and C? Actually B and C intersect because B=[1,5], C=[2,6] overlap. So invalid. If we remove C, have A and B, which intersect. So indeed no candidate. So correct.
Now, what about scenario with two intervals that are identical and a third that is disjoint: A=[1,2], B=[1,2], C=[3,4]. Edges: (A,B) only. total=1, degrees: A=1, B=1, C=0. So both A and B are candidates. Removing A leaves B and C (disjoint), valid. Removing B similar. Removing C leaves A and B intersecting, invalid. So candidates A,B. Good.
Now, scenario with three intervals: A and B intersect, and also A and C intersect, but B and C also intersect only at a single point that is exactly the boundary? For example, A=[1,4], B=[3,5], C=[5,7]? B and C: B ends at 5, C starts at 5 -> disjoint. So no edge. So star. Good.
Now, scenario where B and C overlap only at a point that is also the end of A? But if they overlap, then edge exists.
Thus condition holds.
Now, is there any case where degree_i == total_edges but i is not valid because after removal there is still an overlapping due to a "chain" where intervals don't directly intersect but there is a point covered by three intervals because of gaps? No, if three intervals cover a point, they all pairwise intersect.
Thus algorithm is correct.
Now, complexity: O(n^2) with n=5000 is 25e6 operations? Actually loop: for i from 0 to n-1, inner loop from i+1 to n-1: total iterations = n*(n-1)/2 ≈ 12.5e6. In each iteration we do a couple of comparisons and possibly increments. So maybe 12.5 million * ~5 operations = ~62.5 million operations. Might be okay in PyPy. In Python 3, 12.5 million simple loops can be done in < 1 second? Actually typical Python can do about 50 million simple operations per second on fast hardware? I'm not sure. 12.5 million is safe for 2 seconds. Usually Codeforces problems with n=5000 and O(n^2) are acceptable in Python if optimized. We'll ensure to use local variables and avoid attribute lookups.
Now, one more possible optimization: we could break early if we find a vertex that has degree > total_edges? Not needed.
Alternatively, we could compute degrees by sorting intervals and using sweepline to detect overlaps, which could be O(n log n) but more complex. Not necessary.
Thus final solution: O(n^2) pairwise intersection detection.
Now, we should also consider that n=1 case, loop from i=0 to 0: inner loop not executed, degrees=[0], total=0, condition true, output 1 and 1. Good.
Now, implement and test with given examples.
I'll write code accordingly.
But wait, there is a nuance: The intervals may have length zero? No, li<ri, so positive length.
Now, is there any scenario where the condition degree_i == total_edges might hold but the set of remaining intervals has an intersection because of intervals that are not pairwise intersecting but still have a common point? That's impossible: if two intervals share a point, they intersect pairwise. So no.
Thus solution stands.
Now, we should also ensure we treat intervals as half-open. Use condition if li < rj and lj < ri.
Test with [1,3) and [2,5): li=1<5 true, lj=2<3 true -> intersect. Good.
Now, could there be a scenario where intervals intersect only at a single point but we treat as non-intersecting because of half-open? For example, [1,3) and [3,5) we said no intersection. But if they were closed intervals, they'd intersect at point 3. But problem says finishing and starting at same moment don't intersect. So correct.
Now, but what about [1,3] and [3,5] if they were integer points? The problem uses integer times but time is continuous, so moment 3 is a point. So they don't intersect. So correct.
Thus we are good.
Now, output: we must print k on first line, and if k>0, print the indices on second line. The problem statement: "Output integer k — amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers — indexes of groups". So if k=0, we just output 0. In sample 3, they output only "0". So we do that.
Now, let's test with n=2, both intersect.
Input:
2
1 2
1 2
Our code: intervals: (1,2) and (1,2). Intersection condition: li=1<rj=2 true, lj=1<ri=2 true -> intersect. So degree each=1, total=1. Candidates both (degree==1). Output: 2 then "1 2". That is valid.
Now, check with n=2, [1,2] and [2,3]: Condition: li=1<3 true, lj=2<2 false => no intersect. degree both 0, total 0, candidates both, output 2 then "1 2". Removing either leaves one interval, no intersections. So valid.
Now, check with n=3: [1,3], [2,4], [3,5] we already did: candidate 2? Let's compute: A=[1,3), B=[2,4), C=[3,5). Intersections: A-B: 1<4 and 2<3 => true; B-C: 2<5 and 3<4 => true; A-C: 1<5 and 3<3? 3<3 false => no. So degrees: A=1, B=2, C=1, total=2. Candidate B. Output 1 and "2". That seems plausible: remove B leaves A and C, which are disjoint? A ends 3, C starts 3 => disjoint, so correct.
Now, check scenario where there is exactly one intersecting pair, but the pair shares a common endpoint? Already accounted.
Now, think about a scenario where intervals are like: [1,4], [2,3], [5,6]. Here A and B intersect, C disjoint from both. Edges: (A,B) only. Degrees: A=1, B=1, C=0 total=1. Candidates A and B. Removing A leaves B and C disjoint? B and C: B ends 3, C starts 5, disjoint. So valid. Removing B leaves A and C, disjoint? A ends 4, C starts 5 => disjoint if 4<5? 4<5 true, so disjoint. So both valid. So output both A and B. Good.
Now, scenario: A=[1,4], B=[2,5], C=[3,6]. All intersect pairwise. No candidate.
Thus algorithm seems correct.
But we must be cautious: The degree condition we derived: degree_i == total_edges. However, is it possible that there are no edges but some intervals are such that they intersect at a point? That would be an edge, so no.
Alright.
Now, we can implement.
But wait, there is a nuance: The intervals are given as (li, ri) with li < ri. Could there be a case where two intervals intersect but our condition li < rj and lj < ri might fail due to integer boundaries if we treat as inclusive? But we are using strict inequalities.
Now, verify with example: [1,3] and [3,5]: li=1<5 true, lj=3<3 false => no intersect. Good.
Now, another subtlety: The input might have intervals where l and r are large, but we compare them as ints, fine.
Now, we need to ensure that we output indices in increasing order. Our candidate list built by iterating i from 0 to n-1 will be increasing automatically.
Now, we should consider test where total_edges > 0 and there is exactly one interval i with degree_i == total_edges, but also there might be another interval j that also has degree_j == total_edges? That would require both to be incident to all edges. If there are at least two edges, can two vertices both be incident to all edges? Suppose edges: (i,j) and (i,k). Then j is not incident to (i,k) unless j = i? Actually j is not in (i,k). So j's degree is 1, total_edges=2. So not equal. If only one edge, both endpoints have degree 1 and total=1, so both equal. So multiple candidates possible only when there is exactly one edge or zero edges.
Now, if there are zero edges, all are candidates.
Thus algorithm yields correct set.
Now, we must ensure that we count edges correctly, including duplicate? Not possible.
Now, what about the possibility that there is an interval that doesn't intersect any other but there is another pair that intersect. Then total_edges >0, that isolated interval has degree 0, not equal to total_edges, so not candidate. Good.
Now, one more nuance: The problem statement: "The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect." It doesn't require that the remaining groups' lessons are pairwise non-intersecting? It says "no two time periods of lessons of the remaining groups intersect." That means for any two groups, their lessons do not intersect. That's pairwise non-intersection. So our interpretation correct.
Now, about large n: 5000. O(n^2) is okay. However, there might be a possibility to further optimize but not needed.
Now, I want to double-check the complexity: For n=5000, loops: sum_{i=0}^{n-1} (n - i - 1) = n(n-1)/2 = 12,497,500. So about 12.5 million. In Python, if we use PyPy, it might take ~0.3-0.5 seconds. But if we use CPython, maybe ~0.8-1.2 seconds. Usually Codeforces time limit 1 sec? Not specified but typical 1-2 secs. Many Python solutions for n=5000 O(n^2) pass if optimized. So okay.
We can also add a micro-optimization: store l and r in lists, then in inner loop use local references.
Implementation:
def solve():
import sys
data = sys.stdin.buffer.read().split()
if not data: return
it = iter(data)
n = int(next(it))
l = [0]*n
r = [0]*n
for i in range(n):
l[i] = int(next(it))
r[i] = int(next(it))
deg = [0]*n
for i in range(n):
li = l[i]
ri = r[i]
for j in range(i+1, n):
if li < r[j] and l[j] < ri:
deg[i] += 1
deg[j] += 1
total = sum(deg)//2
res = [str(i+1) for i in range(n) if deg[i] == total]
out = [str(len(res))]
if res:
out.append(' '.join(res))
sys.stdout.write('\n'.join(out))
Now, test with sample input.
We'll run mental test.
Now, potential pitfalls: integer conversion may be heavy but okay.
Now, one more thought: Could the condition deg[i] == total be affected by rounding? Since total = sum(deg)//2, it's integer. For candidate, deg[i] must equal that integer.
Now, verify with n=1: deg[0]=0, total=0, condition true. Good.
Now, with n=2 both intersect: deg=[1,1], sum=2, total=1, deg[0]==1 true, deg[1]==1 true. Good.
Now, with star of 3: deg center=2, leaves=1, total= (2+1+1)//2 = 4//2=2, center deg=2, leaves deg=1 -> only center.
Now, with triangle: deg each=2, sum=6, total=3, deg each=2 !=3.
Works.
Now, consider scenario where there are multiple edges but some intervals have degree 0. No candidate.
Now, is there any scenario where total_edges is computed incorrectly because we used integer division but sum(deg) must be even. It will be because each edge contributes 2. So fine.
Now, we need to ensure that we treat the intersection condition correctly. We used li < r[j] and l[j] < ri. This is equivalent to li < rj and lj < ri. This is symmetric, good.
Now, confirm with intervals that are large but overlapping. Works.
Now, test with intervals: [1,1000000], [500000,500001], [500001,1000000] (just random). Our condition fine.
Now, confirm that we are not missing any intersecting case due to half-open: Suppose intervals [1,2] and [1,2] exactly same: li=1<2 true, lj=1<2 true -> intersect. So they intersect at all points except maybe endpoint? Actually half-open includes 1 but not 2, they share the same set, so intersect.
Now, confirm that two intervals that just touch at a point: [1,2] and [2,3]: li=1<3 true, lj=2<2 false -> no intersect.
Thus correct.
Now, finalize.
But before finalizing, think if there could be a scenario where after removal, the remaining intervals are pairwise non-intersecting, but the original intersection graph does not satisfy the condition that all edges incident to the removed vertex. Could there be a situation where after removal, no two intervals intersect, but originally there was an intersecting pair that did not involve the removed vertex? If there was an intersecting pair (j,k) that does not involve i, then after removal, if i is removed, j and k remain, and they still intersect. So that can't happen. So original edges must all involve i.
Now, could there be an intersecting pair that originally existed but after removal, due to removal of i, they become non-intersecting? That is impossible because removal of a third party does not affect the relationship between j and k. So if they intersect originally, they still intersect after removal of i. Therefore, all original intersecting pairs must involve i. So condition holds.
Thus necessary and sufficient.
Now, is it possible that originally there is no intersecting pair, but after removal of i, there is an intersecting pair? No.
Thus algorithm is sound.
Now, potential issue: Overlap detection for large n may be time-consuming. But fine.
We could even early break: if we find that there are two intersecting pairs with different vertices not sharing a common vertex, we could conclude no candidate early. However, we still need to compute degrees for all? But if we detect early that there exist two edges that do not share a common vertex, then no vertex can be incident to all edges. But we could still need to compute total edges to know? Not really; we could compute candidates on the fly. But easier to just compute all.
Given n=5000, we just do full.
Now, additional check: In the star case, if the center interval i is valid, but also there could be intervals that are completely inside i but also intersect each other? That would create edges not involving i, so not a star. So condition fails.
Now, let's attempt to produce a random test to verify logic.
Now, think about potential pitfalls with integer boundaries when intervals are like [1,2] and [2,2]? But ri>li, so ri>li, so r is at least l+1. So no zero-length.
Now, I think solution is correct.
Now, but there is another nuance: The problem statement says: "If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect." This implies that intervals are considered closed at start and open at end? Actually typical interpretation: if one finishes at time t and another starts at time t, they don't intersect. So we can treat intervals as [l, r) (includes start, excludes end). Our condition is correct.
Now, is there any scenario where intervals may be considered intersecting if one contains the other entirely? That is included.
Now, final answer.
But wait, there is another approach: compute the maximum depth. But we already have graph approach.
Now, note: The degree condition might be simpler than computing depth.
Now, let's test with more tricky scenario: intervals overlapping such that depth = 2 but the overlapping region is not contiguous? For graph, it's fine.
Now, think about scenario: intervals A=[1,10], B=[2,3], C=[4,5], D=[6,7] where B, C, D are all inside A, but they are disjoint from each other? Actually B, C, D are disjoint (since [2,3], [4,5], [6,7] are disjoint with gaps). Intersections: A intersects with B, C, D. There are no intersections among B, C, D because they are separated. So edges: (A,B), (A,C), (A,D). So total_edges=3, degree_A=3, degree_B=1, etc. So candidate A only. Indeed, remove A, remaining B,C,D are disjoint. So valid.
Now, what if B and C also overlap? Then extra edge (B,C), so total_edges=4, degree_A=3? Actually A would have edges to B, C, D: 3; B would have edges to A and C: 2; C would have edges to A and B: 2; D:1. Total = (3+2+2+1)/2 = 8/2=4. degree_A=3 !=4, so no candidate. So can't fix by removing one.
Thus algorithm works.
Now, I think we have a correct solution.
Now, output formatting: In sample 1, they printed trailing space after 3. Not necessary. We'll not.
Now, final answer.
But wait, there is a potential nuance: The problem might treat intervals as inclusive of both ends? Let's double-check statement: "If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect." If intervals were inclusive of both ends, then if one finishes at time t and another starts at t, they would both include t? Actually if intervals are inclusive, e.g., [1,3] and [3,5], both include time 3, so they would intersect. But statement says they don't. So they are not both inclusive. So either [l, r) or (l, r] works. So our half-open is correct.
Now, another nuance: The problem may treat times as points in time, and a lesson occupies time from l to r inclusive? But they explicitly say that if one finishes and another starts at same moment, they don't intersect. So they consider that the finish moment is not part of the lesson or the start moment not part? It's ambiguous but essentially they treat boundaries as non-overlapping. So half-open is correct.
Thus we are good.
Now, time to produce final answer.
But I will also consider alternative implementations: maybe using sorting and sweep to compute degrees in O(n log n) but not needed.
Now, finalize.
One more test: n=5000 all intervals [i, i+1) for i from 1 to 5000, they are disjoint. Our code will compute degree all 0, total 0, candidates all 5000 indices. Output will be 5000 numbers, which is okay.
Now, test with n=5000 all intervals [1, 1000000] (all identical). Then degree each = n-1 = 4999, total = n*(n-1)/2 ~ 12.5e6. None qualifies, output 0. That's fine.
Now, time complexity: 12.5M loops, each loop has two comparisons and two increments when true. For all identical intervals, all pairs intersect, so increments always. So that might be slower because we do increments for both degrees each time. That's about 12.5M * (2 comparisons + 2 increments) which is still okay. In worst-case, all intervals overlap, degree increments many times. But still within reason: 12.5M * maybe 5-6 operations = ~75M operations, which might be near time limit in Python? Possibly borderline. However, n=5000, all overlapping, total edges = ~12.5M. For each edge we do degree[i] += 1 and degree[j] += 1. That's two increments per edge. So total increments = 2 * edges = ~25M. Plus comparisons (12.5M). So total operations maybe ~37.5M. That might be okay in PyPy (which can handle ~100M operations per second? Actually PyPy is slower for some loops but may still pass within 2 seconds). In Codeforces Python 3, 40 million simple integer ops could be ~2 seconds? Possibly okay. But we need to be safe.
We can optimize by using list of intervals sorted by start, and then for each i, only check j where l_j < r_i, because if l_j >= r_i, then no intersection (since sorted by start). That could reduce number of comparisons when intervals are sparse. But in worst-case all intervals overlapping, we would still compare all pairs. So worst-case still O(n^2). But we could break early in inner loop when l_j >= r_i if we sort. However, that would require sorting and then using index to compare. But then we need to map back to original indices. That adds complexity but could reduce average time. However, we need to compute degrees, and sorting would allow us to compute intersections efficiently, maybe O(n log n) using sweepline? Actually we could compute for each interval, count how many it intersects by scanning sorted list with two pointers, but pairwise intersections detection for all pairs would still be O(n^2) in worst-case. However, we can compute degree by counting overlapping intervals for each i using a sweep to get a set of intervals that are open, but we need pairwise counts. Actually, we could compute the intersection graph edges more efficiently using interval tree? But n=5000, simple O(n^2) is simplest.
Given constraints, many Python solutions on Codeforces for similar problems (e.g., 5000 intervals, O(n^2) pairwise check) pass. I think it's fine.
But to be extra safe, we can implement with some micro-optimizations:
Use local variable for deg list and l, r lists.
Use range_i = range(i+1, n).
Use ri = r[i] and li = l[i] outside inner loop.
Use if li < rj and lj < ri: as condition.
We could also try to use if li < r[j] and l[j] < ri: but we may copy to local variable rj and lj each iteration? But that's fine.
We can also pre-store intervals as list of tuples and unpack each time but that is slower.
Better: use two separate arrays.
Now, I'll produce final code.
But before final, let's double-check with a case where intervals are like [1,4], [2,3], [3,5]. We already tested.
Now, think about if there is any possibility of integer overflow in sum? sum(deg) can be up to n*(n-1) = 24,995,000, which fits in Python int.
Now, output.
Now, maybe there is a more efficient way: The degree condition can also be derived as: total intersecting pairs count. If there is exactly one intersecting pair, both are candidates; if there are more, we check if there is a vertex whose degree equals total edges. This is essentially the same.
Thus final answer.
But let's double-check a scenario where there are multiple intersecting pairs, but they all share a common vertex except that there is also a pair that includes that vertex and another vertex, but also there is an overlapping of three intervals at a point but the third interval is the same vertex? That's the star, which we already considered, depth=2 everywhere. Actually star with center i, and leaves j,k that are disjoint. But what if leaves also overlap each other? Then not star. So condition captures.
Now, could there be a scenario where there is a common vertex i for all edges, but still depth>2? For depth>2, we need at least three intervals covering a point. If i is common to all edges, that means any pair of intervals that intersect must include i. Suppose we have three intervals: i, j, k. If they all three cover a point t, then j and k intersect at t, which would be an edge not involving i, contradicting that all edges involve i. So impossible. So depth never exceeds 2.
Thus condition works.
Now, confirm with scenario where intervals j and k intersect at a point but i does not cover that point, but i still intersects both j and k elsewhere. Then there is edge (j,k) not involving i. So all edges not involving i, thus condition fails. So correct.
Thus final solution.
Now, produce final answer.
But there is a subtle nuance: In the case where there are no intersecting pairs, our condition (degree_i == total_edges) becomes degree_i == 0. All intervals have degree 0, so all are candidates. That's correct.
Now, the problem asks to output the indexes of groups where it is possible to cancel the lesson. If there are multiple, output in increasing order.
Thus final code.
I will now write final answer in the required format. ```python
import sys
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
l = [0] * n
r = [0] * n
for i in range(n):
l[i] = int(next(it))
r[i] = int(next(it))
code
deg = [0] * n
# pairwise intersection check
for i in range(n):
li = l[i]
ri = r[i]
for j in range(i + 1, n):
if li < r[j] and l[j] < ri: # half-open intervals intersect
deg[i] += 1
deg[j] += 1
total_edges = sum(deg) // 2
candidates = [str(i + 1) for i in range(n) if deg[i] == total_edges]
out = [str(len(candidates))]
if candidates:
out.append(' '.join(candidates))
sys.stdout.write('\n'.join(out))