We need to solve the problem: Given n (2 ≤ n ≤ 200) and all unions of two distinct original sets (which are disjoint, non-empty). There are m = n*(n-1)/2 unions. Each union is given as a multiset? Actually sets of numbers: but we are given the numbers in arbitrary order. The unions are sets (no duplicates) but the numbers are given in arbitrary order; but since the original sets are disjoint, the union of two sets is just the concatenation of their elements without overlap. So each union list contains exactly the elements from the two original sets combined, no repeats because the sets are disjoint. So each union's size = size(A) + size(B). The union is given as a list of those numbers, possibly in any order.
We are to reconstruct the original sets: n disjoint non-empty subsets of positive integers (values up to 200). The input guarantees there is a solution consistent with the given unions.
Goal: output any valid partition of the universe of numbers that appear? Actually all numbers that appear in unions are from the original sets. Since the original sets are disjoint and non-empty, their union is the set of all numbers that appear in any union. The numbers from the original sets exactly are those that appear. Each number belongs to exactly one original set.
We need to reconstruct the partition.
Approach: This is reminiscent of reconstructing sets from pairwise unions. Known as "Set reconstruction from pairwise unions" problem, similar to "MST from distances" but not exactly. Given disjoint sets, the unions are just concatenations. Each original set's size can be deduced? Possibly.
Let’s denote original sets S1,...,Sn, disjoint. Let their sizes be s1,...,sn (all >=1). The union of Si and Sj has size si+sj. So we have many equations. But we have the actual elements, not just sizes. The unions also contain the actual numbers.
Observation: Since sets are disjoint, each element appears in all unions that involve the set it belongs to, except those unions that are of two sets both not containing it. Specifically, for a given element x, let its original set be S(p). Then x appears in all unions that involve S(p) with any other set S(q) (q != p). That is, x appears in exactly (n-1) unions (one for each pair including S(p) with each other set). Also, x does not appear in any union of two sets that are both not containing x. So frequency of each element across all given unions should be exactly (n-1) if it appears in all unions? Wait, is it possible that an element appears multiple times within the same union? No because unions are sets, each element appears at most once per union. And since original sets are disjoint, each element appears exactly once in the union of two sets only if it belongs to either one. So yes, the count of occurrences of element x across all m unions is exactly the number of pairs (i,j) such that i<j and (i = p or j = p) but not both? Actually for a fixed x ∈ S_p, it appears in union Si ∪ Sj iff p ∈ {i,j}. Number of such pairs is: choose p and any other set: (n-1) pairs. So each element appears exactly (n-1) times in the list of unions. Check: The unions are given for each unordered pair of sets, exactly one union per pair. So yes, frequency f(x) = n-1.
But wait, there is a nuance: Could there be duplicate elements across different original sets? No, they are disjoint. So each element belongs to exactly one original set. So indeed, all numbers that appear in any union should appear exactly (n-1) times? But if n=2, then m=1, each element appears in exactly 1 union (since each element belongs to one of the two sets, and the only union is S1∪S2). So frequency = 1 = n-1 =1. So consistent.
Thus, we can count the occurrences of each number across all given unions. Then the frequencies tell us n: f(x)+1 = n? Actually n = f(x)+1. But careful: For any element that appears, its frequency should be n-1. So n = frequency + 1. So we can compute n from any element's count; but we already know n as input, so it's consistent. However, we can use this to identify which numbers belong to same set? Actually all numbers have same frequency? Since each appears exactly n-1 times, yes. So frequency cannot differentiate sets.
So need more structural info.
Think about each union: it's the set of elements from two original sets. So if we consider the collection of unions, each union is a set that is partitioned into two parts: the elements from Si and from Sj. But we don't know the partition.
We need to reconstruct the partition.
Observations: For any two elements a and b that belong to the same original set, they always appear together in exactly those unions that involve that set, i.e., they co-occur in exactly (n-1) unions? Let's compute: For a,b in same S_p, they appear together in any union Si∪Sj where p is one of i,j. But careful: In union Si∪Sj, both a and b appear if p ∈ {i,j}. They will both appear in that union because the union includes all elements of S_p when S_p is one of the sets. So they appear together in every union that includes S_p. That is, all (n-1) unions where S_p is paired with another set. Also, they do not appear together in any other union because if the union does not include S_p, then neither a nor b appears. So the number of unions containing both a and b is exactly n-1.
Now, consider two elements a and b that belong to different original sets, say a∈S_p, b∈S_q with p≠q. Then they appear together in unions that include both S_p and S_q. Which unions include both? Only the union of S_p and S_q itself (i.e., the specific pair (p,q)). Also, in any union that includes S_p with some other set r (r != p, maybe r=q? only when r=q it's the same pair) and also includes S_q? Actually union Si∪Sj includes exactly two sets. So both a and b can only appear together if the union is exactly S_p ∪ S_q (since that's the only case where both sets are present). In any other union, either a appears without b (if S_p is paired with some r≠q) or b appears without a (if S_q is paired with some r≠p), or neither appears. So a and b appear together in exactly one union.
Thus, the co-occurrence count (i.e., number of unions in which both a and b appear) distinguishes whether a and b are in the same original set (co-occur count = n-1) or different (co-occur count = 1). Since n≥2, n-1 >=1, but for n>2, n-1 >1. So for n>2, we can distinguish: same set => high co-occurrence; different sets => co-occurrence = 1. For n=2, n-1=1, so both same-set and different-set pairs co-occur exactly once? Actually if n=2, there is only one union. For two elements from same set, they both appear in that union, so co-occur = 1. For two elements from different sets, they also both appear, co-occur =1. So for n=2, it's ambiguous. But n=2 is a special case that we need to handle separately.
Thus, for n>2, we can construct a graph of elements, where we connect elements that co-occur in more than 1 union? Actually we can compute for each pair (a,b) how many unions contain both. Since the number of unions is O(n^2) which can be up to ~20000, and number of distinct elements up to 200 (since numbers ≤200 but could be up to 200 distinct numbers? Actually sets could have many elements, but total distinct numbers is limited by 200? Input constraints: numbers aij are between 1 and 200. There could be up to 200 distinct numbers. Also n ≤200, but the total number of elements across all sets could be up to maybe a few hundred? Actually each union size up to 200, and there are up to 19900 unions. The total distinct numbers could be up to 200 because aij ≤200. So the universe U is a subset of {1,...,200}. So at most 200 elements. That's manageable.
We can compute pairwise co-occurrence counts. Then for n>2, we can cluster elements where co-occurrence = n-1 (which is >1) to form the original sets. But we don't know n-1 a priori? But we know n from input, so n-1 known. So compute co-occurrence matrix for all distinct elements. For each pair, if count == n-1, they are in same set; else if count ==1, they are in different sets. But careful: Could there be a pair that appears together in more than n-1? Max possible is number of unions that include both, which is at most n-1 if same set, and exactly 1 if different. So it's fine.
But we need to be careful: If there are elements that appear only in some unions? Actually each element appears exactly n-1 times. So total appearances count is as expected.
Thus, algorithm for n>2:
- Parse all unions, collect all distinct numbers.
- For each union, maintain a list of numbers.
- For each pair of distinct numbers (a,b), count how many unions contain both.
- Then group numbers: each group should be such that for any two numbers within the same group, co-occurrence = n-1; for any two numbers from different groups, co-occurrence = 1.
- Then output each group as a set. Since original sets are non-empty, each group corresponds to an original set.
But need to ensure that groups are consistent. The co-occurrence count should be n-1 if same set. However, there might be some numbers that never appear together because they are from different sets? But they appear together in exactly one union (the union of their sets). That union exists. So they should have co-occurrence count 1. So all pairs should have count either n-1 or 1.
What about n=2? Then all pairs of numbers that appear (which are all numbers) appear together in the only union. So co-occurrence =1 for every pair. Thus we cannot differentiate same vs different. So need another method for n=2.
For n=2, we have two original sets A and B, disjoint, non-empty. Their union is given as a single set (since only one pair). We have one union set U = A ∪ B. We need to partition U into two non-empty disjoint subsets A and B. Are there multiple solutions? Yes, but any is acceptable. However, we must satisfy that the input is derived from such sets. But we need to find any partition. Since we only have one union, there is no further information to uniquely determine A and B. So we can output any non-empty proper partition? But we must guarantee that it matches the fact that the input is constructed from some such partition? Actually the problem statement says: "It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets." So for n=2, there is a specific original partition that generated the union. But we only see the union. Without any additional information, any partition into two non-empty disjoint sets would be a possible original set? Possibly not, because the input is derived from that specific partition. However, the problem says: "If there are several answers to that problem, print any of them." So for n=2, any valid partition (non-empty sets) should be acceptable? But the problem also says "It is guaranteed that there is a solution." So we need to output some solution. The question: Is it always true that any partition into two non-empty sets works? Possibly yes, because the union is just the set, and the process: we have two disjoint non-empty sets A and B; we take union A ∪ B and list it. That union could be produced by many (A,B). So the given data does not contain any constraint to distinguish; thus any partition is acceptable. However, we must ensure that our output sets are disjoint and cover all elements exactly once. So we can just arbitrarily split the union into two non-empty sets (maybe each as a singleton if possible). But is it possible that the union size is 1? No, because each set is non-empty, union size at least 2. But union size could be 2? Example: sets {1} and {2}, union {1,2}. Then we can split as {1} and {2}. If union has more elements, we could split arbitrarily.
But careful: Could there be any hidden constraints like the original sets must be those that produce exactly the given unions? For n=2, there's only one union, so any partition yields that union. So indeed any partition is consistent. So we can output any.
But wait: The problem also says: "He had written out the numbers in the unions in an arbitrary order." That means the order within the union is arbitrary, but the union set is exactly the set of numbers from the two sets. So for n=2, we know the set but not the partition.
Thus, for n=2, we can simply output, e.g., the first element as one set (size 1) and the rest as the other set, ensuring both non-empty. Or we could output something like half-half.
But also note: For n>2, the co-occurrence method should work. However, there may be edge cases: If n=3, n-1=2. So same set pairs co-occur in 2 unions, different sets co-occur in 1 union. This works.
Now we must consider the complexity: number of distinct elements up to 200. Number of unions up to 19900. For each union, we need to record its elements. Then to compute pairwise co-occurrence, we could use a bitset representation for each union? But number of unions large, but elements only 200, so we can create a 200x200 matrix of counts initialized zero. For each union, we have its list of numbers. For each pair (a,b) in that union, increment cooc[a][b] and cooc[b][a]. That is O(total size of all unions * average set size)? In worst case, each union size can be up to 200, and there are up to 19900 unions, total numbers could be up to 19900*200 = 3.98 million, which is okay. Pairs within each union: For a union of size k, we need to increment for each pair of numbers within that union. That would be O(k^2) per union, which could be huge: if each union size is ~200, then each union contributes ~20000 pairs, times 19900 unions gives ~400 million, too big. So need to avoid O(k^2) per union.
Instead, we can compute co-occurrence differently: Since each element appears in exactly n-1 unions (which might be up to 199). But we can compute for each element, list of unions that contain it. Then for each pair of distinct elements, compute the intersection count of their union lists. That would be O(|U|^2 * (average list size)) = O(200^2 * 199) ≈ 8 million, which is fine. So better approach:
- Assign each union an index.
- For each distinct number x, maintain a list (or a boolean array of length m) indicating which unions contain x. But m can be up to 19900, so a bitset of 19900 bits is about 2500 bytes per element, times 200 = 500KB, okay. But then computing intersection counts between pairs by bitwise AND and popcount could be efficient. Or we can simply for each x, store a set of union indices (like vector). Since each x appears in exactly n-1 unions, the list size is at most 199. So for each pair (x,y), we can compute common count by merging two sorted lists of size ≤199, which is O(199+199)=O(1). So total pairs 200*200/2 ≈ 20000, times 200 ≈ 4 million operations, fine.
Implementation steps for n>2:
- Read n.
- Read m = n*(n-1)/2 lines. For each line, read k and then k numbers. Store each union as a vector of its numbers. Also, we could store for each number, the list of union indices it appears in.
- Collect all distinct numbers. Since numbers are between 1 and 200, we can have an array present[201] flag.
- For each union i, for each number x in union, add i to appearances[x] (list).
- After reading all, we know n. Compute targetSame = n-1.
- Initialize DSU (disjoint set union) or just build groups using condition: For each pair of distinct numbers (x,y) that are present:
- Compute common = count of common union indices between appearances[x] and appearances[y].
- If common == targetSame, then x and y must be in the same original set. If common == 1, they are in different sets. If something else, maybe error but guaranteed solvable.
- Use this to merge groups: if common == targetSame, union(x,y). If common != targetSame (i.e., 1) we don't union.
- But note: For n>2, targetSame >1. So we can safely use that condition.
- After processing all pairs, we should have exactly n groups, each corresponding to an original set. But we need to verify that groups are consistent: For any two numbers from different groups, the common count should be 1. However, if we just union based on targetSame, we may still have some pairs that are in same group but with common count not targetSame? That could happen if some numbers appear only? But they must appear. But we can rely on guarantee.
- Then output each group: For each group, print its size and its elements in any order.
But we must be careful: There might be numbers that are singletons (appear alone in their set) but then they have size 1. They will be grouped only with themselves? Actually if a set has size 1, then that number appears alone; it will not have any other number in same set, so it won't be merged with anyone because there is no pair with common == targetSame (since no other element in its set). So it remains as a singleton group. That's fine.
Now, about DSU: For up to 200 elements, we can simply use a simple array of labels and BFS to find groups: We can start with each element as its own group, then for each pair if common == targetSame, merge. After merging, we will get some groups. But note: It could happen that due to transitive property, if a,b are same set and b,c are same set, then a,c are same set. Our merging ensures that.
But is it possible that two numbers from same set have common count < targetSame? Wait, earlier we argued that for any two elements in same set, they appear together in all unions that include that set, which is exactly n-1. So common count should equal n-1. That is correct as long as there are no duplicate unions? The input guarantees the unions are exactly for each pair of sets, no duplicates. So it's accurate.
But there is a subtlety: If a set has size 1, there is no other number in that set to compare; that's fine.
Now, what about n=2 case: targetSame =1. Then same-set pairs also have common count 1, so our condition would merge all numbers into one group? Actually if targetSame=1, then both same-set and different-set pairs have common=1, so we cannot differentiate. If we used the condition common == targetSame to merge, then all pairs would merge, resulting in a single group, but we need two groups. So we need to treat n=2 separately.
Thus, handle n=2 separately:
- There is exactly one union (since m=1). Read that line: k and numbers. This is the union set U.
- We need to output two non-empty disjoint sets that partition U.
- Simply: Let the first element of U be a. Output set {a} and set U \ {a} (provided U{a} is non-empty). Since U size >=2, that works.
- Or we could split arbitrarily.
But note: The input guarantee that the original sets are non-empty. So as long as we output two non-empty sets, it's acceptable.
Now, what about n>2 but with targetSame =1? That can't happen because n>2 => n-1 >=2? Actually n could be 2? n>2 => n>=3 => n-1>=2. So targetSame >=2. So fine.
Thus the algorithm is straightforward.
But need to consider potential pitfalls:
-
The numbers are up to 200, but there could be up to 200 distinct numbers. Our DSU can be on these numbers.
-
The union indices can be up to 19900. We'll assign incremental index to each line.
-
We'll need to compute common count for each pair (x,y). Since appearances[x] is a list of indices. Since each element appears exactly n-1 times, the lists are small. We can sort each list (they are naturally added in order of reading, but we can keep as is; to compute common, we could convert to a set (e.g., unordered_set) for fast lookup. But small size, we can just use two-pointer if lists sorted. But we can ensure they are sorted by inserting in increasing order (since we process unions in order, we add index i which is increasing, so each list is already sorted ascending). So we can compute common count by merging two sorted lists.
-
Complexity: For each pair, O(|list_x|+|list_y|) ≤ 2*(n-1) ≤ 398. With about 20000 pairs, that's fine.
-
After building groups via DSU, we need to output them. We need exactly n groups. However, there might be more than n groups if some numbers are not merged? But the total number of original sets is n. So the number of groups we get should be n. Because each original set is a connected component of the graph where edges exist between elements with co-occurrence = n-1. For sets of size >1, the graph on that set is complete (all pairs connected). For sets of size 1, they are isolated nodes. So total components = n. So we should get exactly n groups. If we get more, something is wrong (maybe due to miscomputing targetSame, or n-1 not correct? but we know n). But it should work.
But we must be careful: Could there be two numbers from different sets that also have co-occurrence = n-1? That would require they appear together in all unions that include either of their sets? That would imply that whenever one appears, the other appears, which would mean they are always together. For different sets, that would be false because there is union of the set containing first with some other set not containing the second? Let's examine: Suppose a∈S1, b∈S2. For union S1∪S3 (where S3≠S2), a appears, b does not. So they are not together. So co-occurrence = count of unions where both S1 and S2 appear, which is exactly 1 (the pair S1,S2). So indeed for n>2, there is at least one other set besides S1 and S2, so that union S1∪S3 exists, where b absent. So co-occurrence cannot be n-1. So safe.
Edge cases: n=3, S1 = {a}, S2 = {b}, S3 = {c}. Then unions: S1∪S2 = {a,b}, S1∪S3={a,c}, S2∪S3={b,c}. Then for a and b: they appear together only in union1: count=1. a and c: count=1. b and c: count=1. All pairs have count 1, but n-1=2. But a,b are in different sets, so count=1 as expected. But same-set pairs? There are none because sets are singletons. So all pairs are different-set, count=1. So DSU will not merge any because common !=2. So we get three groups: a alone, b alone, c alone. That's correct.
Now, n=3, S1={a,b}, S2={c}, S3={d}. Then unions: S1∪S2 = {a,b,c}, S1∪S3={a,b,d}, S2∪S3={c,d}. Co-occurrence: a and b: appear together in unions that include S1: both S1∪S2 and S1∪S3 => count=2 = n-1. Good. a and c: together only in S1∪S2 =>1. a and d: together only in S1∪S3 =>1. b and c: 1, b and d:1, c and d: only S2∪S3 =>1. So edges: a-b have high count, others low. So DSU merges a,b into one group; c and d each separate. Groups count=3.
Now, n=4, example given.
So the method works.
Now, we also need to consider if there could be duplicate numbers within the same original set? No, sets have distinct numbers. Since the original sets are sets (presumably with unique elements). The problem statement says "sets consisting of positive integers" and "non-empty sets", implies no duplicates within a set. And they are disjoint. So numbers are unique across all sets. So each number appears exactly once overall.
Now, confirm that frequency of each number across unions is indeed n-1. That's a necessary condition, but we can rely on input guarantee. However, we could also use it as a sanity: compute frequency for each number; if any number has frequency != n-1, maybe the input is invalid? But we can ignore.
Now, implementation details:
-
We'll store appearances as vector for each number from 1 to 200. Initialize empty.
-
We'll read line by line, using string splitting? But simpler: read integers using std::cin. For each union i from 0 to m-1:
- Read k.
- Then for j from 0 to k-1: read a. Mark present[a]=true. Add i to appearances[a]. Possibly store union list? Not needed for later except maybe for sanity? We may not need to store union list; only need appearances per number.
-
After reading, we have list of indices for each number.
-
If n == 2:
-
Since m = 1, we have exactly one union. But we already read that union; we stored appearances, but we need the actual elements of that union. We could store the union list separately. Or we can reconstruct from present numbers: All numbers that appear are exactly the union set. Since m=1, all numbers present appear in that one union. So the set U = all numbers with present flag true. That is indeed the union. So we can output any partition. E.g., take the smallest number as one set, and the rest as other set. But ensure both non-empty: if |U|==1? But cannot because each set non-empty and disjoint; union of two non-empty sets must have at least 2 distinct numbers (since sets disjoint). So |U| >=2. So safe.
-
Implementation: collect vector all; for i in 1..200 if present[i] then all.push_back(i). Then output set1: 1 and all[0]; set2: size = all.size()-1 and remaining elements. Or we could output something else.
-
Else (n > 2):
-
target = n - 1.
-
Initialize DSU of size 201 (ignoring index 0). Or use map for present numbers only.
-
For each pair (x,y) where x<y and present[x] and present[y]:
- Compute common = count_common(appearances[x], appearances[y]).
- If common == target, unite(x,y).
-
After processing, collect groups: For each x present, find root, and add x to group list for that root.
-
The number of groups should be n. But is it guaranteed that after merging based on common == target we get exactly n groups? Let's think: For any two numbers from same original set, they should have common = target, so they will be merged. For numbers from different sets, common = 1 (since target >1), so they will not be merged. However, what about numbers from different sets where target =1? Not applicable. Also what about numbers that are from same set but there is a chain? Merged. So groups correspond exactly to original sets.
-
But we must be careful: Could there be a scenario where common == target for two numbers from different sets? Possibly if the two sets always appear together? But they are different sets, they only appear together in their own union. But what if n=3 and sets S1={a}, S2={b}, S3={c}? common between a and b =1 !=2. So not.
Consider scenario where there are only two sets? That's n=2. For n>2, as argued, there exists at least one other set, so they are not always together.
Now, about DSU: We'll implement with path compression. Since numbers up to 200, simple.
Now, we need to be careful about reading input: The first line is n, then m lines. The input may have extra spaces or newlines; but typical.
Now, test with examples.
Example 1:
n=4. Input as given. After processing, we should get groups: {7}, {2,4}, {1,3}, {5}. That's what output shows. Indeed.
Our algorithm: target = 3. Compute common counts: 2 and 4: they appear together in unions: Which unions contain both? Let's check given unions: {2,7,4} - contains 2 and 4 => count 1? Actually wait, we need to compute accurately. But presumably 2 and 4 appear together in some unions. In the original sets: {2,4} are together. They should appear together in all unions that involve the set containing them, i.e., the set {2,4}. That set is paired with three other sets: {1,3}, {5}, {7}? Actually original sets: {1,3}, {5}, {2,4}, {7}. So unions: {1,3}+{5} = {1,3,5}; {1,3}+{2,4} = {1,3,2,4}; {1,3}+{7} = {1,3,7}; {5}+{2,4} = {5,2,4}; {5}+{7} = {5,7}; {2,4}+{7} = {2,4,7}. So indeed 2 and 4 appear together in unions: {1,3,2,4}, {5,2,4}, {2,4,7} = 3 times = n-1=3. Good. Our algorithm would detect common=3, so they are merged. Similarly 1 and 3 appear together in unions: {1,3,5}, {1,3,2,4}, {1,3,7} = 3 times. So merged. Others are singletons because their set size=1.
Example 2: similarly works.
Example 3: n=3. target=2. Pairs (1,2) appear together in only union {1,2}? Actually given unions: {1,2}, {1,3}, {2,3}. So 1 and 2 appear together only in the first union: count=1 ≠2, so they are not merged. All pairs count=1, so no merges, groups: {1}, {2}, {3}. Output matches.
Now, what about the possibility that within a set, some numbers might not have co-occurrence exactly n-1 due to duplicate appearances? But it should.
Edge Cases:
-
n=200, number of distinct numbers =200 (all numbers 1..200 present). Each set could have varying sizes. For large n, target =199. So common count for same-set pairs =199. That's high. But we need to compute common count by merging two lists of size 199 each. That's fine.
-
The number of unions m = n*(n-1)/2 can be up to 19900. But each element appears in exactly n-1 unions, which is at most 199. So lists are small.
Now, we need to ensure we correctly compute common count. Since appearances lists are sorted, we can do two-pointer counting.
Implementation in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int m = n*(n-1)/2;
vector<vector<int>> unions(m); // maybe not needed
vector<vector<int>> appearances(201); // index 1..200
vector<bool> present(201, false);
for (int i = 0; i < m; ++i) {
int k;
cin >> k;
vector<int> cur(k);
for (int j = 0; j < k; ++j) {
int x;
cin >> x;
cur[j] = x;
present[x] = true;
appearances[x].push_back(i);
}
// maybe store cur for later? Not needed.
}
if (n == 2) {
vector<int> all;
for (int x = 1; x <= 200; ++x) if (present[x]) all.push_back(x);
// output two sets
// set1: first element, set2: rest
int sz1 = 1;
int a = all[0];
cout << sz1 << " " << a << endl;
int sz2 = all.size() - 1;
cout << sz2;
for (int i = 1; i < all.size(); ++i) cout << " " << all[i];
cout << endl;
} else {
int target = n - 1;
// DSU
vector<int> parent(201);
for (int i = 1; i <= 200; ++i) parent[i] = i;
function<int(int)> find = [&](int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
};
auto unite = [&](int x, int y) {
int rx = find(x), ry = find(y);
if (rx != ry) parent[ry] = rx;
};
// Preprocess: ensure appearances lists are sorted? They are because we added in order.
// For each pair of distinct numbers present
vector<int> nums;
for (int x = 1; x <= 200; ++x) if (present[x]) nums.push_back(x);
int N = nums.size();
for (int i = 0; i < N; ++i) {
for (int j = i+1; j < N; ++j) {
int a = nums[i], b = nums[j];
// compute common count
const vector<int>& la = appearances[a];
const vector<int>& lb = appearances[b];
int p = 0, q = 0;
int common = 0;
while (p < la.size() && q < lb.size()) {
if (la[p] == lb[q]) {
++common; ++p; ++q;
} else if (la[p] < lb[q]) {
++p;
} else {
++q;
}
}
if (common == target) {
unite(a, b);
} else {
// if common != target, they should be 1 (different sets) or maybe 0? Could be 0 if two numbers never appear together? But they must appear together at least in the union of their sets? If they are in different sets, they appear together exactly once (the union of those two sets). So common should be at least 1. Could it be 0? If one of them is not present? But all numbers appear. And for any two distinct numbers from different sets, there is exactly one union that contains both (the union of their respective sets). So common should be 1. So not 0. But we don't need to check.
}
}
}
// Collect groups
unordered_map<int, vector<int>> groups;
for (int x : nums) {
int root = find(x);
groups[root].push_back(x);
}
// groups.size() should be n
// output each group
for (auto& [root, vec] : groups) {
cout << vec.size();
for (int v : vec) cout << " " << v;
cout << endl;
}
}
return 0;
}
Check if output format matches: need spaces, each line first number is count of elements in set, then elements separated by spaces. Should print exactly n lines. Our groups count should be n. But there might be a situation where groups.size() > n because some numbers were not merged with others but there are more numbers than n? Actually total numbers distinct maybe > n? Yes, total numbers can be up to 200, n is at most 200, but it's possible that there are more numbers than n (e.g., each set has multiple elements). The number of groups is exactly n (the number of original sets). So groups.size() should be n. Our merging should produce exactly n groups. But what if there is a set that has only one element, then that element is a group by itself. That's fine. So groups.size() will equal n. However, we must be cautious: Is it possible that due to transitive merging, we might merge across sets erroneously if some pair from different sets also has common == target? We argued it's impossible for n>2. So groups.size() should be exactly n.
But we need to ensure we process all pairs; if we miss merging some same-set pair because of computing common incorrectly? Not likely.
Now, we can test on given examples.
But before finalizing, let's think about potential issues:
-
In step computing common count, we rely on appearances lists to be sorted. Since we add indices in increasing order as we read unions, they are sorted.
-
For n>2, target = n-1. But consider n=3, target=2. For pair from same set with size >1, they appear together in unions including that set: there are n-1 = 2 unions. So common=2. Good. For pair from different sets, common=1. So condition works.
-
What about n=3 and a set of size 1? Then there is no pair from same set. So merging doesn't happen; groups are singletons; count of groups = number of numbers = 3 = n? Wait if all sets are singletons, then number of numbers = n. So groups count = number of numbers, which is n. That matches. For n=3, with sets of sizes 1,1,1, we have 3 numbers, each isolated, groups.size()=3, correct.
But if n=3 and one set has size 2, another size 1, another size 1, then total numbers = 4, groups count = 3 (the two numbers in the size-2 set are merged into one group, the other two singletons). So groups.size()=3.
Thus, total groups count should equal n.
Now, what if total numbers > n and we do DSU merging, we might get fewer groups than n if some numbers from different sets are accidentally merged. That would be an error but as argued not possible.
Now, are there any pitfalls regarding the case when n>2 but target = n-1 may be as high as 199, and common count for same set pairs is exactly 199. But are we sure that each element appears in exactly n-1 unions? Yes, because each original set is paired with each other set exactly once. However, what if there are duplicate unions? The problem states exactly n*(n-1)/2 unions, each from a distinct pair of sets. So yes.
But what about an element that appears in fewer unions because its set is not included in all pairs? Actually each set is paired with each of the other n-1 sets, so its elements appear in exactly those n-1 unions. So frequency = n-1.
Now, consider a pair of elements from the same set: they appear together in exactly those n-1 unions where their set appears. So common = n-1.
Thus, algorithm is solid.
Now, check for n=2 case: If we mistakenly run the n>2 code for n=2, target=1, then for any pair, common =1, so they would all merge into one group, resulting groups.size()=1, not 2. So we must handle separately.
Now, is there any scenario for n>2 where some pair from same set might also have common count less than n-1? Possibly if the sets are not all of size >? No, if they are in the same set, they are always together when that set appears. But is it possible that the union of two sets includes only one of them due to some weird? No, because the union includes all elements of both sets. So yes, they always appear together in every union where their set appears. So common = number of unions containing that set = n-1.
Now, about implementation details: When reading input, we need to handle that the unions are given in arbitrary order, but we don't care about order.
Now, edge case: The numbers may not be contiguous from 1 to 200; only those present.
Now, we should also consider the possibility that there might be numbers that appear in the input but are not present in any union? That's impossible; they appear in at least one union because they belong to some set, and that set is paired with at least one other set (since n>=2), so they appear.
Now, testing with sample:
Input example 1:
4
3 2 7 4
3 1 7 3
3 5 4 2
3 1 3 5
4 3 1 2 4
2 5 7
Our code: n=4, m=6. Read 6 unions. For each number, appearances. Then target=3. Compute pairs.
Check: 2 and 4: appearances[2] = which unions? Unions (0-index): line1 (union0): {2,7,4} includes 2; line3 (union2? careful order) but let's compute quickly: union0: 2,7,4; union1: 1,7,3; union2:5,4,2; union3:1,3,5; union4:3,1,2,4; union5:5,7. So appearances:
2: unions 0,2,4 -> indices 0,2,4.
4: unions 0,2,4 -> indices 0,2,4.
Common = 3 -> merge.
1: unions 1,3,4 -> 1,3,4.
3: unions 1,3,4 -> 1,3,4.
Common=3 -> merge.
5: unions 2,3,5 -> 2,3,5.
7: unions 0,1,5 -> 0,1,5.
common between 5 and 7: 5 appears in 2,3,5; 7 appears in 0,1,5; intersection only union5? Actually 5's list: 2,3,5; 7's list: 0,1,5; common = {5} => size 1, not 3 -> not merge.
Others: 2 with 1? appearances: 2:0,2,4; 1:1,3,4; common = {4}? Actually union4 index4 appears in both: 2 has 4; 1 has 4; so common=1 -> not merge. etc.
Thus groups: root(2)=root(4) group1; root(1)=root(3) group2; root(5) group3; root(7) group4. Groups size: 2,2,1,1. Output order may differ but acceptable.
Now, output in any order. The sample output had "1 7" on first line, then "2 2 4", then "2 1 3", then "1 5". That's a valid grouping.
Our code would output groups in arbitrary order (based on map iteration). That's fine.
Now, example 2: similar.
Now, example 3: n=3, m=3, target=2. appearances:
1: unions0,1? Actually unions: 1 2 -> union0; 1 3 -> union1; 2 3 -> union2. So appearances[1] = {0,1}; appearances[2] = {0,2}; appearances[3] = {1,2}. Pair (1,2): common = intersection of {0,1} and {0,2} = {0} -> size 1, not 2 -> no merge. Similarly others. So groups: {1},{2},{3}. Output.
Now, we need to ensure DSU works even if we call unite on same root multiple times; fine.
Now, consider a scenario where numbers are up to 200 but not all present; we only process present ones. DSU parent array of size 201 with default parent for absent numbers but we don't use them.
Now, important: The condition common == target for merging works only if target > 1. For n=3, target=2; ok.
Now, there is another subtlety: The input guarantee that there is a solution, but might there be multiple possible partitions that satisfy the co-occurrence conditions? For n>2, the partition is uniquely determined (since co-occurrence counts uniquely identify which elements are together). Because if two elements are together in n-1 unions, they must be in same set; if not, they are in different sets. So the partition is forced. So our algorithm yields the unique correct partition. So output is determined except order.
Now, check n=2: multiple answers, any works.
Now, confirm constraints: The numbers aij are between 1 and 200. So we can allocate arrays of size 201.
Now, about memory: appearances as vector of vector of size 201, each with up to 199 ints, fine.
Now, potential issues: The input might be large; using cin may be fine. Could use scanf for speed but not necessary.
Now, we must ensure to read all m lines correctly. After reading n, we must read exactly m lines. Some lines may have leading or trailing spaces but that's fine.
Now, test with an additional case: n=3, sets: {1,2,3} (size3), {4}, {5}. Then unions: S1∪S2 = {1,2,3,4}; S1∪S3 = {1,2,3,5}; S2∪S3 = {4,5}. For numbers 1,2,3: each appears in two unions (with S2 and S3). They appear together in both those unions? Yes, all three appear together in both unions that include S1. So pairwise common count = 2 (n-1=2). So they get merged. 4 appears in unions: with S1 and with S3? Actually S2={4}, unions: S1∪S2 and S2∪S3. So appearances[4] = indices of those two unions. 5 appears in S1∪S3 and S2∪S3 -> two unions. Pair (4,5): common = union S2∪S3 only ->1. So groups: {1,2,3}, {4}, {5}. So good.
Now, what about scenario where a set has size 1; then that element has no other element to pair with, so it stands alone.
Now, what about scenario where numbers appear with frequency less than n-1? That would be invalid input; but guarantee ensures valid.
Now, potential pitfalls: If there are duplicate numbers across different unions? They are distinct numbers, so fine.
Now, the DSU approach merges based on common == target. But we must be careful: Could there be a pair from same set with common count less than target because the two numbers might not appear together in some union that includes their set? That would happen if the union is not fully recorded? For example, if the union line omits some number? But by construction, the union includes all elements of both sets. So not possible. So safe.
Now, we should also consider the case where the original sets have duplicate numbers? Not allowed.
Now, the algorithm appears correct.
But wait: There is one more nuance: The unions are given as "sets" of numbers, but the problem statement says: "He had written out the numbers in the unions in an arbitrary order." It doesn't say that the unions are sets, but rather they are "unions of two different sets", which as sets are defined without duplicates, so they are sets. So each union list contains distinct numbers. So our treatment as sets is correct.
Now, but there is a catch: The input lines may contain repeated numbers within a union? Possibly if the original sets have overlapping numbers? But problem says original sets are non-empty and no two have common elements. So they are disjoint. So unions have no duplicates. So each union list is just a list of distinct numbers. So it's a set.
Now, we might also consider alternative solution: Since each element appears exactly n-1 times, we can identify the smallest set by finding element with minimal list? But not needed.
Now, is there any scenario where our algorithm might produce groups count less than n? That would happen if we merge across different sets because of common == target erroneously. Could that happen? Let's think: For two numbers from different sets, they appear together only in the union of those two sets. Could that union be counted multiple times? No, only one union corresponds to that pair. So common = 1. So not equal to target if target >1. So safe.
But what if target = 1 (n=2) we treat separately.
Thus, algorithm stands.
Now, we should also think about the possibility that there are missing numbers? But all numbers that appear in any union are from original sets. So we will output sets that cover exactly those numbers. That's what required.
Now, we should check the output format: print on n lines, each line: first number is size of set, then elements. Example output: "1 7 " (note trailing space? but typical without trailing space). We'll output without trailing space after last number, but a trailing space is acceptable. We'll follow typical: print size, then for each element print space then element. Could have trailing space, but fine.
Now, what about the order of sets? Any order is acceptable.
Now, let's test with a custom case to ensure DSU merges correctly.
Case: n=4, sets: {1}, {2}, {3}, {4} all singletons. Then unions: all pairs: 6 unions each of size 2. For each number, it appears in 3 unions (n-1=3). Pairwise common count: For any two distinct numbers, they appear together only in the union of their two sets, i.e., exactly one union. So common=1. Since target=3, no merges. Groups: 4 groups. Good.
Case: n=4, sets: {1,2}, {3}, {4}, {5}. Then unions: S1∪S2? Actually sets: A={1,2}, B={3}, C={4}, D={5}. Unions: A+B={1,2,3}; A+C={1,2,4}; A+D={1,2,5}; B+C={3,4}; B+D={3,5}; C+D={4,5}. For numbers 1 and 2: appear together in unions containing A: those are A+B, A+C, A+D => 3 unions. So common=3 target=3 -> merge. Others: 1 and 3 appear together only in A+B ->1. So not merged. Groups: {1,2}, {3}, {4}, {5}. Good.
Now, consider scenario where a set has size >1 and there is also another set with size >1. Then numbers within each set have common = target; numbers across sets have common = 1. So merges only within sets.
Now, is there any possibility that two numbers from different sets have common count = target? That would require they appear together in all unions that include either of their sets. For them to appear together, both sets must be present. The union that includes both sets is exactly one. For them to also appear together in unions that include only one of them, the other number must also be present in those unions, meaning it belongs to the other set that is present? If we consider union of set A with some third set C: this union includes A's numbers but not B's numbers unless C = B. So if we want both a (from A) and b (from B) to appear in union A∪C, then b must be in that union, implying b ∈ A∪C, but b ∈ B, disjoint from A, so b must be in C, meaning C = B. So only when C is B does b appear. So the only unions containing both a and b are those that include both A and B, i.e., exactly one union. So common cannot be >1. So safe.
Thus algorithm is correct.
Now, the only possible nuance: When n is large (200) and there are many elements (200), we compute common for each pair ( ~20k pairs ) using two-pointer on lists of size up to 199. That's fine.
Now, we should implement count_common efficiently. We'll use two pointers.
Now, I should also consider if there is any scenario where appearances lists are not sorted due to reading order? Since we read unions sequentially and add index i to each number's list in that order, indices are increasing, so lists are sorted. Good.
Now, what about numbers that appear in exactly n-1 unions? That's all numbers.
Now, potential bug: In n>2 case, we might have groups.size() not equal n due to some numbers not being merged but there being more groups than n. That would happen if some numbers that should be in same set are not merged because common count not target. Could that happen if there are duplicate unions? No. But maybe if the input has some numbers that appear in fewer unions due to a missing union? But guarantee says constructed correctly.
But just in case, we could add a fallback: if groups.size() != n, then we might need to do something else? But not needed.
Now, test with n=2 case: we should not use DSU. In the sample, no n=2 example. We'll produce output that partitions the union arbitrarily.
But also note: In n=2, we have exactly m=1 union. However, our reading loop reads m lines. That's fine. After reading, we have appearances for numbers. But we need the actual list of numbers in that union. We have the list stored in cur? We didn't store cur; we could reconstruct from present numbers as they all appear in that one union. That works.
But what if there are numbers that appear but not in that union? impossible. So we can get all present numbers.
Now, output two lines: first set size 1 and that element, second set rest. But must ensure both non-empty: if there is exactly 2 numbers, both sets size 1. If more, second set size >=2.
Now, is there any requirement that the sets be printed in any order, but must be exactly n sets? Yes.
Now, could there be multiple correct partitions for n>2? As argued, the partition is unique due to co-occurrence pattern. So only one.
Now, confirm that for n>2, target = n-1 is known. So DSU works.
Now, think about if there are numbers that appear in the input but do not appear in all unions? Actually they appear in n-1 unions; that's fixed.
Now, we might also use the frequency to verify n: compute frequency of any number, n = freq+1. But we already have n from input. So it's consistent.
Now, potential alternative approach: Build graph of numbers, connect if they appear together in at least 2 unions. For n>2, that yields cliques per original set. But DSU with threshold target is fine.
Now, I'll implement.
Before final code, test with a manual case:
Input:
3
2 1 2
2 1 3
2 2 3
Our code n=3>2, target=2. appearances:
1: {0,1}
2: {0,2}
3: {1,2}
pairs: (1,2): common=0? Actually intersection of {0,1} and {0,2} = {0} => size 1, not 2 -> no merge. (1,3): {0,1} ∩ {1,2} = {1} ->1, no merge. (2,3): {0,2} ∩ {1,2} = {2} ->1, no merge. groups: three singletons, size 1 each. Output 3 lines: 1 1, 1 2, 1 3 (in some order). Acceptable.
Now, if n=2: Input:
2
3 1 2 3
Interpretation: Two sets, union = {1,2,3}. Our code: present numbers = {1,2,3}. Output: set1: 1 1; set2: 2 2 3? That's valid. But could also be {2} and {1,3} etc. Any is acceptable.
Now, is it guaranteed that for n=2, the union set size >=2? Yes because both sets non-empty and disjoint.
Now, I think the solution is ready.
But I'll double-check if there is any corner case where n>2 but target = n-1 may equal 1? n>2 => n>=3 => n-1>=2, so not.
Now, code might have issues with reading: The input lines may have leading/trailing spaces, but cin handles.
Now, we might need to use faster I/O if necessary. But constraints are moderate.
Now, think about memory: storing unions themselves is not needed. So we can skip storing unions; only store appearances.
Now, potential issue: When reading unions, we need to know which union index we are at. We'll just loop i from 0 to m-1.
Now, after building groups, we need to output n lines. However, what if groups.size() is not n? That would indicate a bug. But we trust input.
Now, implement.
But wait: The problem statement says: "He wrote out all possible unions of two different sets on n·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order." This implies that each union is written as a list (maybe not sorted), and the pieces of paper are shuffled, meaning the order of unions in the input is arbitrary. But we don't need order.
Now, confirm that the unions are exactly for each pair of different sets, no duplicates. So each pair appears exactly once.
Now, we must be careful: The input may include unions that are not in any particular order, but our algorithm uses union indices only to compute co-occurrence; the actual index values don't matter. So fine.
Now, test with an edge case: n=200, but each set could be of size 1, so total numbers=200, each appears in 199 unions. For any two distinct numbers, they appear together only in the union of their two sets, i.e., exactly 1 union. So common=1 for all pairs. Since target=199, no merges, we'll have 200 groups. But n=200, so groups.size()=200, correct.
But wait: if n=200 and each set size 1, then number of distinct numbers = n =200. So groups count =200. That's correct.
Now, if n=200 and some sets have size >1, total numbers <=200, but n is number of sets. So total numbers can be less than n? No, because each set is non-empty, so total numbers >= n. Since max distinct numbers is 200, we must have n ≤ 200. So n could be close to 200, and some sets have size 1, others size >1. So total numbers can be exactly 200, and n could be less than 200? Actually n ≤ 200, and total numbers ≤ 200. For n close to 200, many sets must be size 1 because total numbers at least n, and max 200, so it's possible that all sets are size 1 (n=200, total numbers=200). Or some sets size >1 forces n < total numbers? Actually total numbers = sum of sizes. Since n ≤ 200 and total numbers ≤200, it's possible that n < total numbers if some sets have size >1. For example, n=100, each set size 2 => total numbers=200. So n can be smaller than total numbers. In such case, our DSU should produce exactly n groups, not total numbers. Because groups are sets; they correspond to original sets, not individual numbers. So groups.size() should be n, which could be less than total numbers. So DSU merges numbers within same set, reducing count from total numbers to n. So that's correct.
Now, consider the possibility that two numbers from same set might have common count less than target if there is some union where the set appears but one of the numbers is missing? That would only happen if the set is not constant? But sets are fixed; all its elements appear in every union that includes that set. So they always appear together. So common = n-1.
Thus, the algorithm is correct.
Now, I'll implement in C++.
But I want to consider if there is any alternative scenario that could break the assumption: The problem says "He wrote out all possible unions of two different sets" but could it be that he wrote them out as multisets (i.e., if there are duplicate numbers within a union, they'd appear multiple times)? The problem says "he wrote out the numbers in the unions in an arbitrary order." It doesn't explicitly state that each union is a set, but it says "unions of two different sets" which are sets. So the union is a set (no duplicates). Also, the sample shows unions like "3 2 7 4" which are three distinct numbers. So it's a set. So we are good.
Now, one more nuance: The input may contain numbers that are not present in any union? That would contradict guarantee because all numbers from original sets appear in at least one union. But could there be numbers that appear in the unions but not in the original sets? No, because unions only consist of numbers from the original sets. So the set of all numbers appearing is exactly the union of all original sets. So we output exactly that.
Now, let's think about the possibility of ambiguous grouping for n>2? Suppose there are two numbers that always appear together in all unions. Could they be from different sets? For them to always appear together, they must be in the same set as argued. But is it possible that due to the structure of sizes, two numbers from different sets happen to appear together in all unions? For that, they would need to be present in every union. For a number to be present in every union, it must belong to a set that is part of every pair? That would require that set to be paired with every other set, which is true for every set: each set appears in all unions with other sets. So if a number belongs to set A, it appears in all unions where A is present, i.e., all unions involving A. For it to appear in a union not involving A, it would have to belong to another set as well, but sets are disjoint. So a number from set A does not appear in unions that do not involve A. So for two numbers from different sets A and B to appear together in all unions, they would need to be present in unions that do not involve A or B? Actually "appear together in all unions" meaning in every union of the whole collection? That would require they appear together in each of the m unions. But there is union of A with some C ≠ B: In that union, A's number appears, but B's number does not, so they don't appear together. So they cannot co-occur in that union. So they cannot appear together in all unions. Thus the only way two numbers have co-occurrence count equal to m (i.e., all unions) would be if there are only two sets? Actually if n=2, m=1, trivial. For n>2, it's impossible.
So uniqueness stands.
Now, what about the DSU merging condition: we unite if common == target. But what if we accidentally unite two numbers from different sets because common equals target due to some coincidences? As argued impossible.
Thus, solution is correct.
Now, implementation details:
- Use int arrays of size 201 for parent, present, appearances (vector[201]).
- For reading, we can use scanf for speed. But cin with sync off is fine.
Now, consider time: For each union, we read numbers and push_back index to appearances. That's O(total numbers). Then pair loop: O(K^2 * average list size) where K = number of distinct numbers ≤ 200. So fine.
Now, I'll code.
But before final, let's run through some tricky examples to see if any subtle case could cause common count to be less than target for same set elements.
Suppose a set has size >1, and there is a union that includes that set, but the union line may have omitted one of the numbers due to error? But guarantee says input is constructed correctly, so not.
Now, there is also possibility that the original sets are not necessarily all used? They are all used because we have unions for all pairs. So each set appears in n-1 unions.
Thus, all good.
Now, what about memory: appearances as vector[201] each of size up to 199, total ~40k integers, fine.
Now, finalize solution.
Edge Cases and Verification:
-
n=200, m=19900, each union size could be up to 200, total numbers up to 3,980,000. Our reading loop handles that many numbers. That's okay (4 million ints). Input size can be large, but within typical limits (4 million integers is maybe 16 MB). Acceptable.
-
In the pair loop, we have O(K^2 * L) where K≤200, L≤199 => about 200*200/2 * 400 = 8 million operations, fine.
Now, I'll produce final answer.
One more thought: Could there be a scenario where we have numbers that are not present but parent array includes them? We only consider present numbers, so fine.
Now, implement DSU.
Now, final code.
But I'll also consider if there is a simpler approach: Since for each number, we have its list of union indices, we could compare these lists directly: two numbers belong to the same set iff their lists are identical (since they appear in exactly the same unions). Because if they are in same set, they appear in all unions where that set appears, which is exactly n-1 specific unions. And if they are in different sets, they appear in different sets of unions: each appears in unions involving its own set. Could the lists be identical for different sets? Let's check: For a∈A, b∈B, A≠B. The list for a: all unions where A is present. The list for b: all unions where B is present. Are these lists ever identical? They would be identical if the sets of unions containing A equals those containing B. That would mean that for every other set C, the union A∪C is present iff B∪C is present. Since all pairs are present, the set of unions containing A is the set of all pairs (A, X) for X≠A. Similarly for B: all pairs (B, X) for X≠B. These two sets are different because (A,B) is in both? Actually (A,B) is in the list for A (as union with B) and also for B (as union with A). But the others: For X not equal to A or B, (A,X) is in A's list but (B,X) is in B's list. For the lists to be identical, we would need a bijection between such X, but the lists are sets of indices, not by set names. Since there are n-1 unions for each, and (A,B) is common, the remaining n-2 unions for A are with sets other than A,B; for B are with sets other than A,B. For the lists to be identical, the set of other sets for A must equal the set of other sets for B, which would imply that the collection of other sets is the same, i.e., A and B share the same set of other sets, which is true because the other sets are all sets except themselves. So the other sets are all except A and all except B; they differ unless n=2? Let's examine: For n=3, A's other sets: B and C. B's other sets: A and C. Are these sets of unions the same? A's unions: A-B, A-C. B's unions: A-B, B-C. They are not identical because A-C vs B-C are different. So the lists are different. For n>2, they are different. So we could also group numbers by identical appearances lists. Since each number's appearances list is exactly the list of union indices where its set appears. And numbers from same set have identical lists (since they appear in exactly the same unions). Numbers from different sets have different lists. So we could simply group by the list (as a sorted vector or as a bitset). That might be simpler: no need to compute pairwise common counts; just compute for each number its appearances list (sorted). Then group numbers that have exactly the same list. The number of groups should be n. But we must be careful: For n=2, the lists for numbers in set A are the single union index (the only union is A∪B). For numbers in set B, also the same union index? Actually both sets appear in the same union? Wait, for n=2, there is only one union: A∪B. That union contains all numbers from both sets. So every number appears in that one union. So all numbers have the same appearances list (just {0}). So grouping by identical lists would put all numbers together, which is wrong because we need two sets. So for n=2, this approach fails. But for n>2, it works. However, our co-occurrence method also needs separate handling for n=2. So either works. But grouping by identical lists might be easier: no need to compute pairwise common, just use map<vector> groups. But we need to compare vectors; we could convert appearances list to a signature (e.g., a bitset of size m). But m can be up to 19900, bitset of that size is 19900 bits ~ 2.5KB per number, times 200 = 500KB, acceptable. But easier: Since each list size is small (n-1), we could just store as vector and use map with vector as key (C++ can compare vectors). But vector comparison is lexicographic; that's fine as long as we ensure they are sorted (they are). However, the number of distinct lists is exactly n, because each set yields a distinct list of union indices (the set of indices where that set appears). Are these lists guaranteed to be distinct for n>2? As argued, yes. So grouping by list yields the original sets. For n=2, they all have same list, so we need special handling. That's a valid alternative.
But is it always true that appearances lists for numbers in the same set are identical? Yes, because they appear in exactly the same unions (whenever their set appears). So they share the same list of union indices. However, careful: The union indices are assigned arbitrarily based on the order of the shuffled pieces of paper. So the list for numbers from set A will be the set of indices of unions that involve A. Since the unions are shuffled, the actual numeric indices are not meaningful, but the set of indices is the same for all numbers in A. So yes, identical.
Thus, we can simply group numbers by their appearances list (as a sorted vector, which is already sorted because we added in order). Then, for n>2, we should get n groups. For n=2, we get 1 group, so we need special case.
This method avoids computing pairwise common counts, and is simpler.
But is there any scenario where two different sets could have the same appearances list? For them to have same set of union indices, the sets of unions that involve each set must be the same. As argued, for n>2, they differ. Let's prove: Suppose we have sets A and B. The set of unions involving A is { (A, X) for all X ≠ A }. The set of unions involving B is { (B, X) for all X ≠ B }. Since there exists at least one other set C distinct from A and B (since n>2), then the union (A, C) is in A's list but not in B's list because (B, C) is in B's list, but (A, C) ≠ (B, C) as unordered pairs? However, the unions are just sets; we are talking about the specific union pieces of paper. Each union corresponds to an unordered pair of sets. So the union (A, C) is a specific piece of paper, and (B, C) is a different piece of paper. So they have different indices. So the set of indices for A includes the index of (A,C), while for B includes index of (B,C). Since these indices are distinct (different pieces of paper), the lists differ. So indeed, for n>2, the appearances lists are distinct for different original sets. So grouping by them yields correct partition.
Thus, we can adopt the grouping-by-appearances method, which is simpler and possibly more efficient (no need to compute pairwise intersections). However, we still need to handle n=2 specially.
But note: The appearances lists are vectors of union indices. For n>2, each list has size n-1, which could be up to 199. There could be up to 200 numbers, so grouping by vector (which is up to 199 ints) using map is okay. The map will have at most 200 keys, each key a vector. That's fine.
Alternatively, we can compute a hash of the list, but standard map with vector works (vector defines < operator). So we can do:
map<vector<int>, vector<int>> groups;
for (int x : present_numbers) {
groups[appearances[x]].push_back(x);
}
Then, if n == 2, we need to split the single group into two groups arbitrarily. But careful: In n=2 case, groups.size() will be 1 (since all numbers have same appearances list). So we will output two sets from that single group by partitioning it arbitrarily.
If n>2, groups.size() should be n. We'll output each group as a set.
Thus, we don't need DSU at all. That is simpler and less error-prone.
But is there any possibility that for n>2, two different sets could accidentally have the same appearances list because the union indices assigned to (A,C) and (B,C) are the same? That would require that (A,C) and (B,C) be the same piece of paper, which is impossible because each union corresponds to a unique pair of sets. So they are distinct. So lists differ.
But what if the number of sets is n>2, but some set has size 1, and another set also size 1; they will have different lists because the union indices that involve each set differ. So grouping works.
Thus, grouping by appearances list is a more straightforward algorithm.
We must be careful about the fact that appearances lists for numbers within the same set are identical only if we consider the exact list of indices (including duplicates). Since we only push index once per union, and each number appears in each union at most once, the list is the set of indices of unions containing that number. Since the number appears exactly once per such union, the list contains each index exactly once. So it's a set.
Thus, grouping by appearances vector (which is sorted) will cluster numbers from same set.
Now, we should verify with examples.
Example 1: n=4.
Compute appearances:
2: [0,2,4]
4: [0,2,4] -> same list.
1: [1,3,4]
3: [1,3,4] -> same list.
5: [2,3,5]
7: [0,1,5]
Thus four distinct lists: {0,2,4}, {1,3,4}, {2,3,5}, {0,1,5} -> four groups. Good.
Example 2: Check.
Example 3: n=3, appearances:
1: [0,1]
2: [0,2]
3: [1,2] -> three distinct lists. So groups are three singletons. Good.
Thus, grouping by appearances list yields correct answer for n>2.
For n=2, all numbers have same list: [0] (assuming union index 0). So groups size 1. So we need to split.
Thus, our algorithm:
- Read n, m = n*(n-1)/2.
- For each union i from 0..m-1:
read k, then k numbers.
for each x: present[x]=true; appearances[x].push_back(i).
- If n == 2:
- Collect all numbers present.
- Split into two non-empty subsets arbitrarily (e.g., first element alone, rest).
- Output.
- Else:
- Use map<vector, vector> groups.
- For each x with present true: groups[appearances[x]].push_back(x).
- The map size should be n.
- Output each group: size and elements.
Edge Cases: Must ensure appearances vectors are sorted. Since we add i in increasing order, they are.
Complexities: same as before.
Now, consider if there could be multiple numbers with identical appearances list but from different sets? As argued, no for n>2. But could there be a scenario where two sets have exactly the same set of union indices? That would require that the set of other sets for each is the same. Since for set A, the other sets are all except A; for set B, all except B. These sets are equal only if A = B, because the complement of {A} equals complement of {B} iff A=B. Since the universal set is all sets, the sets of other sets differ because A is not in A's other sets, but A is in B's other sets if B != A. Actually check: For set A, the other sets are U \ {A}. For set B, they are U \ {B}. These two sets are equal iff {A} = {B} i.e., A=B. So indeed they are different. So the set of unions (i.e., the set of pairs) involving A and involving B are different sets of pairs. Since each pair corresponds to a distinct piece of paper with a unique index, the indices sets are different. So appearances lists differ.
Thus, algorithm is sound.
Now, what about n>2 but some sets have identical size and maybe the lists are permutations? But the list values are indices; they are not just a pattern, they are specific numbers. They could be the same if the mapping of indices accidentally maps the two sets to the same set of indices? Wait, the indices are just the order we read the unions. The union (A,B) is a specific piece of paper. It is impossible that the set of pieces of paper that involve A equals the set that involve B, because (A,C) for some C is different from (B,C). So they cannot be equal as sets of pieces of paper. So safe.
Thus, the grouping method works.
Now, implementation details:
-
Use map<vector, vector>. But vector as key in map requires operator< defined, which is lexicographic. Since vectors are sorted and distinct, this works. However, note that if two vectors have the same set of indices but in different order, they'd be considered different if not sorted? But we ensure they are sorted because we inserted in increasing order; so they are naturally sorted. So fine.
-
Could also use unordered_map with a hash of the vector, but we can just use map.
Now, we need to ensure we only consider present numbers. We'll iterate x from 1 to 200, if present[x] then groups[appearances[x]].push_back(x).
Now, potential pitfalls: The appearances vectors for numbers in same set must be exactly identical, including order. Since order is ascending, they are identical.
Now, could there be numbers that belong to the same set but have different appearances lists due to a reading error? No.
Now, test with a custom case: n=3, sets: A={1,2}, B={3}, C={4}. Unions: A+B: {1,2,3} (index0), A+C: {1,2,4} (index1), B+C: {3,4} (index2). Appearances:
1: [0,1]
2: [0,1]
3: [0,2]
4: [1,2]
So groups: [0,1] -> {1,2}; [0,2] -> {3}; [1,2] -> {4}. So three groups. Good.
Now, consider n=2: A={1,2}, B={3}. Union: {1,2,3} (index0). Appearances: 1:[0],2:[0],3:[0]. Groups: only one group with list [0] -> {1,2,3}. Then we split into two sets arbitrarily. Since original was {1,2} and {3}, but any split is acceptable. So output maybe {1} and {2,3} etc.
Thus, algorithm is correct.
Now, let's ensure the output format: print each set on a separate line: first number is the size of the set, then the elements separated by spaces. We'll output as described.
Now, I'll produce final solution using grouping by appearances.
Implementation in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int m = n * (n - 1) / 2;
vector<vector<int>> appearances(201); // 1-indexed
vector<bool> present(201, false);
for (int i = 0; i < m; ++i) {
int k;
cin >> k;
for (int j = 0; j < k; ++j) {
int x;
cin >> x;
present[x] = true;
appearances[x].push_back(i);
}
}
if (n == 2) {
vector<int> all;
for (int x = 1; x <= 200; ++x) {
if (present[x]) all.push_back(x);
}
// output two sets: first element alone, rest as second
cout << "1 " << all[0] << "\n";
cout << all.size() - 1;
for (size_t i = 1; i < all.size(); ++i) {
cout << " " << all[i];
}
cout << "\n";
} else {
map<vector<int>, vector<int>> groups;
for (int x = 1; x <= 200; ++x) {
if (present[x]) {
groups[appearances[x]].push_back(x);
}
}
// groups.size() should be n
for (const auto& [key, vec] : groups) {
cout << vec.size();
for (int v : vec) cout << " " << v;
cout << "\n";
}
}
return 0;
}
But we must be careful: In n=2 case, we need to output exactly two lines. Our code does that. However, if there are more than two sets? That's only for n=2. Good.
Now, test with given examples.
Example 1:
Input as above. n=4, m=6. appearances built. groups size should be 4. Output groups. The order may differ, but any is acceptable.
Example 2: similar.
Example 3: n=3, groups size 3, output each singleton.
Now, confirm that for n=2 case in example? Not provided, but we trust.
Now, one more check: In n>2, is it possible that the groups map has size less than n? That would happen if two different original sets have the same appearances list. As argued impossible. However, could there be numbers from the same set that have different appearances lists due to some anomaly? No. So groups.size() should equal n.
But what if there is a bug: We didn't store the unions, but what if the same number appears multiple times in the same union? The problem doesn't allow duplicates in original sets, and sets are disjoint, so union has distinct numbers. But if the input erroneously included duplicate numbers in a union, our appearances list would still have the union index only once (since we only add once per number per union). But that could cause a number to have fewer appearances? Actually if there is a duplicate in the input line, we would read the same number twice for the same union; we would add the same index to appearances[x] twice, leading to duplicate entries in the vector. That would cause the appearances vector to have duplicates, which would make grouping by vector (including duplicates) potentially mismatch. However, the problem guarantees input is constructed correctly, so this won't happen. But if we want to be safe, we could use a set to avoid duplicates per number per union, but unnecessary.
Thus, final code is fine.
Now, we might want to use faster I/O, but fine.
Now, about memory: appearances as vector[201] each can have up to 199 entries; that's fine.
Now, final answer.
But before finalizing, consider edge case: n=200, all sets have size 1 => total numbers=200, each appears in 199 unions. The appearances vectors for each number are of length 199, each distinct (since each set's union indices set is unique). So map with 200 keys each storing a vector of 199 ints: total memory ~2001994 ~ 160KB, plus overhead, fine.
Now, we should ensure that the map's key is a vector and that copying the vector for each key is okay; we will use the vector from appearances as the key, but we need to note that groups[appearances[x]] will copy the vector (since it's used as key). That's fine.
Alternatively, we could use a map with a hashed signature (like a bitset) to avoid copying large vectors, but 199 ints copying is trivial.
Now, performance: For each x, we do groups[appearances[x]].push_back(x). The map will copy the vector for key lookup. That's okay.
Now, potential issue: In n>2, the appearances vectors are all of the same length (n-1). That might help but not required.
Now, finalize.
But wait: There's a nuance: The appearances list for a number is the list of union indices where it appears. Since the unions are shuffled, the order of indices in the list is the order we read them, which is increasing. So it's sorted. So two numbers from same set will have identical lists. Two numbers from different sets will have different lists. So grouping works.
Now, test with a case where there are multiple numbers in a set, but their appearances lists are identical? Yes.
Now, one more check: The problem statement says: "He wrote out all possible unions of two different sets on n·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order." So the order of unions in input is random, but we assign indices based on input order. So the set of indices for a given original set is the set of positions where that union appears in the shuffled list. This set is random but fixed. Different original sets have different sets of positions because each union paper is unique. So indeed, each original set corresponds to a unique set of indices (the indices of the papers that contain that set). Since the papers are distinct, these index sets are distinct. So grouping works.
Thus, final solution is solid.
Now, we need to produce final answer with explanation.
Now, I'll prepare final answer in the required format: include solution description and code.
But the user asked: "Little Vasya likes ... can you restore the sets by the given pieces of paper?" So we need to output the solution.
Thus, final answer: Provide algorithm explanation and code.
Now, I'll write final message accordingly. The problem can be solved by analyzing how many times each number appears together with others. For two numbers from the same original set, they appear together in exactly (n-1) unions (all unions that include their set). For two numbers from different sets, they appear together in exactly one union (the union of those two sets). When (n>2), this gives a clear distinction.
A simpler observation: For each number, the list of indices of the unions that contain it is exactly the same for all numbers belonging to the same original set, and different for numbers from different sets (because each original set participates in a distinct set of unions). Therefore, we can group numbers by these index lists. The only exception is (n=2), where all numbers share the same list (the only union), so we must split the set of all numbers arbitrarily into two non‑empty parts.
Algorithm
- Read (n) and compute (m = n(n-1)/2).
- For each union (i = 0 \ldots m-1):
- Read its size (k) and then the (k) numbers.
- For each number (x), mark it as present and append (i) to
appearances[x].
- If (n = 2):
- Collect all present numbers.
- Print one number as the first set (size 1) and the remaining numbers as the second set.
- Otherwise ((n > 2)):
- Build a map from the index list (vector of union indices) to a list of numbers having that list.
- For every present number (x), insert (x) into
groups[appearances[x]].
- The map will contain exactly (n) entries, each corresponding to one original set.
- Output each group: its size followed by its elements (any order).
The input guarantees a solution, so the map size will be (n) for (n>2).
Complexities: at most 200 distinct numbers, each appears in at most 199 unions, and there are at most 19900 unions. The grouping step is very fast.
Code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int m = n * (n - 1) / 2;
vector<vector<int>> appearances(201); // numbers 1..200
vector<bool> present(201, false);
for (int i = 0; i < m; ++i) {
int k;
cin >> k;
for (int j = 0; j < k; ++j) {
int x;
cin >> x;
present[x] = true;
appearances[x].push_back(i);
}
}
if (n == 2) {
vector<int> all;
for (int x = 1; x <= 200; ++x)
if (present[x]) all.push_back(x);
// any non‑empty split works
cout << "1 " << all[0] << "\n";
cout << all.size() - 1;
for (size_t i = 1; i < all.size(); ++i)
cout << " " << all[i];
cout << "\n";
} else {
map<vector<int>, vector<int>> groups;
for (int x = 1; x <= 200; ++x) {
if (present[x]) {
groups[appearances[x]].push_back(x);
}
}
for (const auto& [key, vec] : groups) {
cout << vec.size();
for (int v : vec) cout << " " << v;
cout << "\n";
}
}
return 0;
}