We need to solve: given n users, m groups. Each group is a set of users. Two users are friends if they belong to at least one common group. So the friendship graph is defined by: vertices are users, edges connect any two users that appear together in some group. Essentially, each group forms a clique (complete graph) on its members. So the overall graph is the union of cliques: for each group, we connect all pairs within the group.
We need for each user x, the size of the connected component containing x in this friendship graph. Because news spreads along friendship edges; the process essentially reaches all vertices in the same connected component as the starting vertex.
Thus problem reduces to: given n nodes, and m cliques (each group forms a clique), compute the connected components of the graph obtained by taking the union of these cliques. Then output for each node the size of its component.
Constraints: n, m up to 5e5, total sum of group sizes (sum of k_i) up to 5e5. So groups are relatively sparse, but each group can be large. However, constructing the full graph explicitly (all pairwise edges) would be too large if group sizes are large (e.g., group of size 1e5 would yield ~5e9 edges). We need an efficient way to compute connected components.
We can treat groups as connecting sets of nodes. Since groups define cliques, connectivity is transitive: if we have groups connecting nodes, the component is basically the connected components in a hypergraph where groups are hyperedges. Actually, two nodes are directly connected if they share a group. But we can think of the graph as a bipartite graph between users and groups: connect each user to the groups they belong to. Then two users are connected if they are at distance 2 via a group node. The connected components in the user-user graph are exactly the connected components in this bipartite graph when we ignore group nodes? Actually, the bipartite graph (users - groups) is a representation: two users are connected via a group if they share a group. But also connectivity can go through multiple groups: user A -> group1 -> user B -> group2 -> user C. In the user-user graph, A is connected to C via B. In the bipartite graph, A and C are connected if there is a path alternating users and groups. So the connected components in the user-user graph correspond to the connected components in the bipartite graph when considering only user nodes? Actually, if we take the bipartite graph (users U, groups G), and then take the projection onto users (two users are adjacent if they share a neighbor in G), the connectivity in the projection may be larger than connectivity in the bipartite graph? Let's think: In the projection graph, there is an edge between u and v if they share a group. In the bipartite graph, u and v are connected via a path u-g1-u1-g2-...-v. In the projection, that path translates to u connected to u1 via g1, u1 connected to u2 via g2, etc., so there is a path in the projection. Conversely, a path in the projection corresponds to a sequence of such shared-group connections, which can be lifted to a path in the bipartite graph. So the connected components of the projection are exactly the connected components of the bipartite graph after collapsing group nodes? More precisely, in the bipartite graph, consider the connectivity between user nodes (ignoring group nodes as separate entities). Two user nodes are connected in the bipartite graph if there is a path between them (alternating). That is exactly the same as being in the same connected component of the projection. So we can compute connected components on the bipartite graph (U ∪ G). Since total edges in bipartite graph = sum of group sizes ≤ 5e5, we can construct this graph with vertices: n users plus m groups. Then run BFS/DFS to find components. Then for each user, the size of the component (counting only users) is the answer. But careful: The component in the bipartite graph includes both user vertices and group vertices. For each component, the number of user vertices in that component is the size of the corresponding user set. So we can do: For each component, count how many users are in it. Then assign that count to each user in that component.
But is this correct? Let's verify: In the original problem, two users are friends if they belong to a common group. So there is an edge between them directly in the user graph. The connected component of a user in the user graph is the set of users reachable via such edges. In the bipartite graph, if there is a path user A - group1 - user B - group2 - user C, then in the user graph, there is an edge between A and B (via group1) and between B and C (via group2), so A is connected to C via B. So indeed A and C are in the same user component. Conversely, if two users are in the same user component, there is a path of user-user edges, each edge corresponds to a common group; that path can be expanded into a bipartite path (by inserting the group between each pair). So they are connected in the bipartite graph. So the bipartite graph's user connectivity (ignoring group nodes) is equivalent.
Thus we can compute components in the bipartite graph (n+m nodes, edges = sum of group sizes). Since sum ≤ 5e5, this is feasible. However, note m can be up to 5e5, so total vertices up to 1e6, edges 5e5. That's fine.
Implementation:
- assign IDs: users from 1..n, groups from n+1 .. n+m.
- For each group i (1-indexed groups), read k_i, then list of user IDs. For each user u in list, add an undirected edge between u and group_node = n+i. That's the bipartite graph.
- Then run BFS/DFS to find connected components. Since graph is undirected, we can use union-find (DSU) as well. Actually, DSU is simpler: union each user in a group with the group node? But DSU normally works on a set of elements; we want to union all nodes that are connected. However, groups and users are distinct types. But DSU can treat all nodes (n+m) as elements. For each group, we want to connect all its members with the group node (or even directly connect all members among themselves? DSU can union all users within a group with each other efficiently via a "representative" method: for each group, take the first user (if any) and union it with the group node, and then union all other users with the group node. That would connect all users in the group via the group node, which is sufficient to capture connectivity: because any two users in the same group become connected via the group node in DSU. Indeed, if we union each user with the group node, then all users in the group will be in the same DSU set (via the group node). And if a user belongs to multiple groups, those groups will be unioned via that user. So connectivity is correctly captured.
Thus we can use DSU on n+m elements. The edges are implicit: for each group, we have edges between group node and each member. That's exactly what we need.
After processing all groups, we have DSU sets. Then we need for each user, the size of its component counting only users. So we need for each DSU root, the number of user nodes in that set. We can compute an array userCount[root] = number of users in that set. To compute, we iterate over all users (1..n), find root, and increment count. Then for each user, answer = userCount[root(user)].
But careful: DSU also includes group nodes. When we count users, we ignore groups. So that's fine.
Complexities: DSU operations O(α(N)) per union, total unions = sum of group sizes (since for each member we union with group node). That's ≤ 5e5. So total O(5e5 α(N)). Memory: DSU parent array of size n+m up to 1e6, that's fine.
One nuance: groups could have size 0. Then they have no members, they are isolated nodes; they don't affect users. So we can ignore them (but still create DSU node? But they are isolated; we can just not create edges, but they are just nodes that don't connect to any user; they won't affect user components. However, if we allocate DSU for all groups, they remain separate sets; we can ignore them because we only count users. So it's fine.
Edge Cases: If a group has size 1, then that user gets connected to the group node, but no other user. That's fine.
Thus solution: DSU.
But wait: Is there any subtlety? In the original friendship graph, if two users are in the same group, they are directly connected. In DSU with group node, they become connected via the group node: i.e., they share the same set, which is correct. However, if there is a group with many users, DSU will union them all with the group node. That yields the same connectivity as directly unioning each pair? Yes, because unioning with a common node makes them all in same set. So it's fine.
Now, DSU on up to 1e6 nodes, unions up to 5e5. That's fine.
Alternative approach: BFS on bipartite graph, but DSU is simpler.
So algorithm:
-
Read n, m.
-
Initialize DSU with size n+m.
-
For i in 1..m:
read k_i.
if k_i > 0:
read first user f.
union( f, n+i ) // group node
for each of the remaining k_i-1 users u:
union( u, n+i )
else (k_i = 0):
// nothing to union
-
After all unions, compute size of each set counting only users.
Create array sizeUser of length n+m, init 0.
For u in 1..n:
root = find(u)
sizeUser[root]++
-
For each user u in 1..n:
answer[u] = sizeUser[find(u)]
Print answers.
But wait: Are we sure that unioning each user with the group node is sufficient to capture connectivity across groups? Consider two groups G1 and G2. If a user A belongs to G1, and also user B belongs to G1 and G2? Actually, user belongs to multiple groups. For user U, we will union U with each group node it belongs to. So if U belongs to G1 and G2, then G1 and G2 become connected via U. So yes.
Thus correct.
Now, double-check with example:
n=7,m=5
Groups:
1: 3 2 5 4 -> group1 (node 8) connected to users 2,5,4.
2: 0 -> group2 (node 9) no connections.
3: 2 1 2 -> group3 (node 10) connected to 1,2.
4: 1 1 -> group4 (node 11) connected to 1.
5: 2 6 7 -> group5 (node 12) connected to 6,7.
Now DSU:
- group1 connects 2,5,4 => set A: {2,4,5,8}
- group3 connects 1 and 2 => union 1 with group3 (10), and union 2 with group3. Since 2 already in set A via group1, find(2)=root of set A, union(1,2) will merge set containing 1 (with group3) with set A => set A now includes 1,2,4,5,8,10. Also group4 connects 1 (already same set) => just union 1 with group4 (11) -> set A includes group4 as well.
- group5 connects 6,7 => set B: {6,7,12}.
Thus components:
Set A users: 1,2,4,5 -> size 4.
Set B users: 6,7 -> size 2.
User 3? Not in any group? Actually groups: group1 includes 2,5,4 (no 3), group3 includes 1,2 (no 3), group4 includes 1 (no 3), group5 includes 6,7. So user 3 is isolated? But group2 had 0, so user 3 not in any group. In the friendship graph, user 3 has no friends because it doesn't appear in any group, so its component size should be 1. But our DSU: we never union user 3 with any group. So user 3 remains in its own set (only user 3). sizeUser[find(3)] = 1. But wait, group2 is node 9, but user 3 is not connected to it because group2 has no members. So yes, user 3 is isolated. So answer: users: 1->4, 2->4, 3->1, 4->4, 5->4, 6->2, 7->2. But expected output is: 4 4 1 4 4 2 2. That matches.
Thus solution works.
Now, consider constraints: n,m up to 5e5, sum k_i <= 5e5. That's good. DSU size: up to 1,000,000, which is fine. We'll implement DSU with path compression and union by size/rank.
Potential pitfalls:
- Input reading: need to be fast. Use sys.stdin.read().
- Memory: parent array of size n+m+1, size array for DSU maybe ints.
- When counting user sizes, we only count users, not groups.
Implementation details:
- Let's index users 0..n-1? Or 1..n? We'll use 0-index for easier Python list? But groups from n .. n+m-1. We'll do 0-index for users: 0..n-1. Group IDs: n + i for i from 0..m-1.
- DSU arrays length = total = n+m.
- For each group i from 0 to m-1:
read k_i, then list of users (given as 1-indexed). Convert to 0-index: user-1.
If k_i > 0:
first = users[0]
union(first, n+i)
for each u in users[1:]:
union(u, n+i)
else: pass.
- Then after unions:
userCount = [0]*(n+m)
for u in range(n):
root = find(u)
userCount[root] += 1
Then for u in range(n):
ans = userCount[find(u)]
store.
Print ans for each user.
Edge Cases: groups can have size 1. Then union user with group node; that user becomes connected to that group node only. If user belongs only to that group, then its component will consist of that user and the group node, but userCount for that root will be 1, so answer 1, which is correct: no other users share that group, so it's isolated in user graph? Actually if group size=1, that user has no friends, because friendship requires two users in same group. So component size should be 1. Good.
Now, is it possible that two users are connected indirectly via a chain of groups but never share a group directly? Yes, DSU captures that via group nodes.
Thus solution is straightforward.
But we need to confirm that DSU on group nodes yields the same connectivity as the user graph's connected components. Formal reasoning: The user graph is the projection of the bipartite graph onto users. In the bipartite graph, two users are connected if there is a path alternating users and groups. In DSU we union each user with its groups, effectively connecting user to group. Then DSU connectivity on the bipartite graph: two nodes are in same set if they are connected by a path. So if two users are connected in bipartite graph, they will be in same DSU set. Conversely, if they are in same DSU set, they are connected in bipartite graph. So DSU sets correspond to bipartite graph components. And as argued, the user graph components correspond to bipartite graph components when ignoring group nodes. So DSU correctly yields user components.
Thus answer is correct.
Now, potential optimization: Instead of storing DSU for groups, we could process groups with a union-find on users only, using the idea of connecting all users in a group efficiently without iterating over all pairs. This is often done by connecting each user in a group to the first user in that group, or using a "virtual node" per group. The virtual node approach is exactly what we did. So it's fine.
Implementation details: Use sys.stdin.buffer.read() to read all input fast. Parse integers.
Let's code:
Pseudo:
import sys
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
total = n + m
parent = list(range(total))
size = [1]*total # for union by size, but we may use rank
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a,b):
ra = find(a)
rb = find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
# Process groups
for i in range(m):
k = int(next(it))
if k == 0:
continue
# read k users
users = [int(next(it))-1 for _ in range(k)]
group_node = n + i
# union first user with group
union(users[0], group_node)
for u in users[1:]:
union(u, group_node)
# Count users per component
comp_sizes = [0]*total
for u in range(n):
root = find(u)
comp_sizes[root] += 1
# Output answers
out = []
for u in range(n):
root = find(u)
out.append(str(comp_sizes[root]))
sys.stdout.write(' '.join(out))
if name == 'main':
main()
Check: This counts groups also? But comp_sizes only increments for users, so it's fine.
Now, test with sample.
We should consider memory: comp_sizes of length total (1e6) is fine.
But note: In DSU, the union by size uses size array for all nodes, but we also use that array for union decisions. After unions, size[root] includes both users and groups. But we don't use that. Instead we compute user-only counts separately.
But what if there is a group with size 0? That group node remains isolated, but we might still count it later in comp_sizes for users? No, we only count users, so it doesn't matter.
Potential pitfall: In union we use size array for union by size. Initially size for all nodes 1. That's fine. But note that group nodes may have size 1 initially; as we union users, size will count users+groups. That's okay.
Now, we need to think about time: find operations per union: each union does two finds. For each user in group, we union with group node. So total unions = sum of k_i <= 5e5, so total find operations ~ 2*5e5 = 1e6, plus final finds for counting: n finds = up to 5e5, and another n finds for output = 5e5. Total finds ~ 2e6, with path compression and union by size, very fast.
Thus solution passes.
But wait: The problem statement says: "two users are friends if there is at least one group such that both of them belong to this group." So if a group has size 0, obviously no friendships. For size 1, no friendships. So all good.
Thus answer.
But is there any nuance? Could there be multiple groups? Yes.
Now, I'd like to think about correctness in more formal sense. Yes.
Edge case: n up to 5e5, m up to 5e5, sum k_i up to 5e5. So total number of users plus groups = up to 1e6. DSU arrays of size 1e6 of ints: that's 8 MB if using Python ints? Actually Python ints are objects, but list of ints is references to Python int objects, each int is about 28 bytes, so 1e6 ints = 28 MB, plus parent list and size list, that's ~56 MB, might be okay for memory limit? Usually memory limit 256 MB or 512 MB, but Python can be memory heavy. However, we need to be careful: 1e6 Python ints in a list: each int is 28 bytes (for 64-bit CPython). So two lists => ~56 MB. Plus other data (e.g., the input list, etc.) maybe around 80-100 MB. Should be okay if memory limit is >=256 MB. But we can try to reduce memory: We could use array('I') from array module, or use built-in list but that's fine. However, typical Codeforces memory limit is 256 MB, Python solution with DSU on 1e6 nodes should pass. But we need to check: parent list of length 1e6 of ints uses about 8 MB? Actually Python ints are objects, but small ints are cached? Not for large numbers. In CPython, int is 28 bytes (on 64-bit). So 1e6 ints = 28 MB. Two lists = 56 MB. Also comp_sizes list another 28 MB -> total 84 MB. That's okay. Plus some overhead for input data (the list of integers from reading all input uses memory, but we parse from bytes and produce a list of bytes strings? Actually .split() returns list of bytes objects, which could be huge: total input size is up to sum of numbers? Input: n,m and then each group's k_i and user ids. Sum k_i ≤ 5e5, plus m numbers for k_i. So total numbers: 2 + m + sum k_i ≤ 2 + 5e5 + 5e5 = about 1e6 numbers. Each bytes object maybe 1-6 bytes plus overhead. That could be significant (maybe > 50 MB). Actually splitting the whole input into list of byte strings is memory heavy: each byte string is a separate object. Better to use map with sys.stdin.buffer.read().split() but that still creates a list of byte strings. However, there is an alternative: use sys.stdin.buffer.read().split() is common and usually passes for up to 1e6 numbers. I think it's okay. But we can also use a generator reading ints from stdin using a custom fast int reader to avoid storing all strings. Let's estimate: 1e6 numbers, each up to 5e5, average length maybe 2-6 digits, so total bytes maybe ~5-6 MB. Splitting into list of bytes objects: each bytes object is a slice of the original bytes? Actually .split() returns list of byte strings that are substrings of the original bytes, each byte string is a new object? In CPython, split on bytes returns list of bytes objects that are slices (copies?) I'm not entirely sure. Usually .split() on bytes returns list of bytes objects each as a separate object, copying the data? Possibly each sub-string is a new bytes object (since bytes are immutable and slicing creates a copy). Actually, in Python, splitting bytes returns a list of bytes objects, each a copy of a segment. So memory overhead could be large: 1e6 bytes objects, each with overhead maybe 33 bytes + data length. Data length average maybe 2-6 bytes. So worst-case maybe ~40 MB? Actually each bytes object overhead: PyObject header (around 33 bytes) plus the data (size). So 1e6 objects could be ~33 MB overhead + data. Data total maybe 5 MB, so ~38 MB. Combined with DSU arrays 84 MB gives ~122 MB. Plus other overhead maybe within 256 MB. So it's acceptable. But we can optimize memory by using a custom fast int reader that yields ints without storing all tokens. But it's not necessary likely.
But Python DSU with 1e6 nodes might be borderline for time? Let's think: 1e6 find operations with path compression, each find is quite fast. Typically DSU with 1e6 operations in Python can run within 0.5-1 second if optimized. With total operations around 2e6, it might be around 1-2 seconds, which should pass on typical time limit 2 sec? Could be okay, but we can micro-optimize: use iterative find with path compression as above, union by size.
But note: The sum of k_i <= 5e5, so total unions only 5e5, not 1e6. So find calls: for each union, 2 finds; also final counting: n finds (5e5) and another n finds (5e5). Total find calls: 2*5e5 + 5e5 + 5e5 = 2e6. That's okay.
We need to be careful about recursion depth if we used recursive find; use iterative.
Thus solution is acceptable.
Now, confirm with some more cases:
Case: n=1,m=0. Then no groups. DSU: only user 0. comp_sizes[0]=1. output: 1. Ok.
Case: n=5,m=1, group with k=5: all users. DSU: group node union with all users. Then all users same set. comp_sizes for root count=5. Output all 5.
Case: n=5,m=2: group1: users 1,2; group2: users 3,4; user5 isolated. DSU: group1 node connects 1,2; group2 node connects 3,4; 5 alone. So output: 2,2,2,2,1? Wait, users 1 and 2 are connected, so they both have component size 2. Users 3 and 4: size 2. User5:1. Good.
Now, could there be any subtlety with large groups: DSU works fine.
Thus answer is correct.
But wait: The problem statement says: "Initially, some user x receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know." That is indeed the connected component.
Thus solution is to output component sizes.
Thus final code as above.
But I recall that there is another approach: using BFS on the bipartite graph might be simpler but DSU is fine.
One more nuance: The DSU approach uses virtual nodes for groups, which increases total nodes to n+m. But note that m can be up to 5e5, and n up to 5e5, total 1e6, which is fine.
Alternative: Without virtual nodes, we could connect users directly using union-find with a "representative" for each group: for each group, take first user as pivot, then union all other users with that pivot. That would require only unions between users, no extra nodes, but we still need to process each group's members. That would also work and avoid extra nodes. However, there is a subtlety: If a group has only one user, then no unions; fine. If a group has many users, we union them all with the first. That would require about (k_i-1) unions per group, same as before. So total unions still sum(k_i) <= 5e5. That would use only n DSU nodes. So memory would be slightly less. Is there any advantage? With virtual nodes, we have to account for group nodes, but we also need to compute component sizes ignoring group nodes. With direct user unions, we can compute component sizes directly. So maybe that is simpler: For each group, if k_i > 0, take first user f, then for each other user u in group, union(f, u). That directly makes all users in the group connected. However, there is a catch: If a group has size 2, that union is direct. If a group has size 3, we union the other two with the first. That connects them all. If a user belongs to multiple groups, the unions across groups will connect all groups via that user because the user is already in some component. So the connectivity is captured correctly. Indeed, the user graph's edges are all pairs within each group. Union by making the group a star (all to first) ensures that all users in the group become in same set. This is essentially the same as using a virtual node but with one less node per group. So we can avoid group nodes. Then component sizes are directly counted by DSU on users only. That's more memory efficient. So why would we use virtual nodes? Virtual nodes are useful when we need to process many groups efficiently with linking, but here both ways are similar. However, there is a subtle difference: Using virtual nodes, we union each user with the group node; using direct star union, we union each user with the first user. Both require the same number of unions. But direct star union might result in longer chains if we always pick the same first user? DSU handles that with path compression, so it's fine. But there is a potential inefficiency: Suppose we have a group with many users, and the first user is isolated before this group. Then we union each other user with that first. After that, the first becomes root perhaps. That's okay. There's no performance issue.
Thus we can implement DSU on only n nodes. That reduces memory and avoids counting group nodes. Let's evaluate:
Implementation:
- DSU parent array size n.
- For each group:
- read list of users (converted to 0-index)
- if len > 0:
first = users[0]
for each u in users[1:]:
union(first, u)
That's it.
But careful: If a group has size 0, do nothing. If a group has size 1, do nothing.
After all unions, we need component sizes: For each user find root, increment count.
Then for each user output its component size.
Check with sample: groups:
1: users [2,5,4] (0-index: 1,4,3?) Actually careful: Input users are 1-indexed. In sample: group1: 2 5 4 -> indices 1,4,3 (since 2->1, 5->4, 4->3). first = user 1 (index 1). union(1,4) and union(1,3). So component: {1,3,4}? Actually user indices: 1,3,4 (2,4,5 in 1-index). That's users 2,4,5. Then group3: 1 2 -> indices 0,1. first=0, union(0,1). Now user0 and user1 are unioned, and user1 is already in component {1,3,4}? Wait, we need to see: after group1, component contains users 1,3,4 (2,4,5). Now group3: users 0 and 1. first=0, union(0,1) -> union(0,1). This will merge component of user1 (which includes 1,3,4) with user0. So component becomes {0,1,3,4} (users 1,2,4,5). That's size 4. group4: users [1] -> size1 no union. group5: users [6,7] (0-index 5,6). first=5, union(5,6) -> component {5,6} (users 6,7). So final component sizes: user0 (1) size4, user1 (2) size4, user2 (3) isolated -> size1, user3 (4) size4, user4 (5) size4, user5 (6) size2, user6 (7) size2. That matches expected.
Thus direct star union works. However, there is a nuance: In the original friendship graph, if a group has size k, then all pairs are friends. In our DSU star approach, we only union each user with a single representative (first user). This ensures connectivity: all users become connected because they are all directly connected to the first user through the DSU union operations. But does this correctly capture that they are in the same component? Yes, because the DSU connectivity is exactly the transitive closure of the union operations. Since we added edges (union) between each user and the first user, the DSU will consider all of them in the same set. So that set corresponds to a connected component in the graph where edges are between each user and the first user? But wait, the actual user graph includes edges between any two users in the group, not just edges to the first user. However, DSU connectivity only requires that there is a path between any two users. In our representation, two non-first users are not directly connected by an edge, but they are both connected to the first user, so there is a path of length 2 through the first user. In the original graph, they are directly connected (edge of length 1). But that doesn't matter for connectivity: as long as they are in the same connected component, they will eventually be reachable. In DSU, we only need to capture that they are in the same component, not necessarily that the edge exists. So it's fine.
But is there any scenario where this star union might incorrectly connect users? Consider a group with users A, B, C. We union A with B and A with C. That puts A, B, C in the same set. That's correct. Now consider another group with users C, D, E. We union C (as first) with D and E. Then we connect sets {A,B,C} and {D,E} via union of C with D/E? Actually if we union C with D, that will merge the sets containing C and D. Since C is already in set {A,B,C}, that merges D and E (since we also union C with E) into that set. So final set {A,B,C,D,E}. That correctly reflects that all these users are connected because of groups: A-B-C (via first group) and C-D-E (via second group). So indeed connectivity is captured.
Thus direct star union works perfectly, without needing virtual nodes.
So we can implement DSU with only n nodes. That reduces memory to about 2 arrays of size n (5e5) which is ~ 25e528 = 28 MB? Actually each int 28 bytes, for two arrays ~28 MB? Wait: 5e5 ints * 28 = 14 MB per list. Two lists: 28 MB. Plus comp_sizes (another list) maybe 14 MB, total 42 MB. That's less. But we still have input tokens. So it's better.
But is there any drawback? With virtual nodes, we needed to count only users, but with direct unions we don't have group nodes, so counting is straightforward: just count per root. So it's simpler.
Thus I'll adopt the direct union approach.
But careful: When we do star union, we only union each user with the first user. However, what if a group has size 0? skip. What if a group has size 1? no union. That's fine.
Thus algorithm:
-
DSU on n users.
-
For each group i from 1 to m:
read k_i.
if k_i > 0:
read list users (1-indexed, convert to 0-index)
representative = users[0]
for each u in users[1:]:
union(representative, u)
-
After processing all groups, compute for each root the number of users in its component: count[root] += 1.
-
For each user, answer = count[find(u)].
That's all.
Now, time: unions = sum (k_i - 1 for groups with k_i>0) <= total sum k_i <= 5e5, so at most 5e5 unions. That's fine.
Edge Cases:
- Large group: e.g., group with 5e5 users. We will read all users and do 5e5-1 unions. That's okay.
- Many groups with small size.
One nuance: The groups can have size 0. But input may contain lines with "0" and then no numbers; we need to read accordingly.
Now, we must ensure we don't have any off-by-one errors.
Implementation details:
We'll read all ints quickly.
Pseudo:
def solve():
import sys
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
m = int(next(it))
parent = list(range(n))
size = [1]*n # for union by size
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra = find(a)
rb = find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
for i in range(m):
k = int(next(it))
if k == 0:
continue
# read k user IDs
# We need to get all k ints; but we can process one by one without storing all?
# We'll read first, then loop for k-1.
first = int(next(it)) - 1
for _ in range(k-1):
u = int(next(it)) - 1
union(first, u)
# count component sizes
comp_size = [0]*n
for u in range(n):
root = find(u)
comp_size[root] += 1
out = [str(comp_size[find(u)]) for u in range(n)]
sys.stdout.write(' '.join(out))
That works.
But is it necessary to union all users with the first? Could there be a scenario where unioning with first is not sufficient to connect all users? Suppose a group with users A, B, C. If we union first (A) with B and A with C, then indeed A, B, C are in same set. So yes.
Now, check with group where we might have to consider that some unions might be redundant but that's okay.
Thus this simpler DSU is better.
But wait: Is there any scenario where the connectivity via groups is not fully captured by pairwise unions via a representative? Let's think about the graph: The user graph edges are all pairs within each group. This graph's connected components can be computed by taking each group as a set and adding edges between all pairs. The DSU star method essentially adds edges from each user to the representative. That yields a graph that is a subgraph of the original graph? Actually, the star edges are a subset of the original edges (since the representative is also a user, so edge between representative and any other user exists in the original graph because they are in the same group). So the star graph is a spanning subgraph of the clique. Since it's a subgraph, connectivity in the star graph implies connectivity in the original graph? Actually, if the star graph is a subgraph, then any path in the star graph is also a path in the original graph (since all edges in star graph are also edges in original graph). The original graph may have more edges, but that only adds connectivity, not remove. So if two nodes are connected in the star graph, they are connected in original. Conversely, if they are connected in original, are they necessarily connected in the star graph? Possibly yes, because the star graph still contains enough edges to maintain connectivity within each group: all nodes in a group are connected to the representative, so the group is connected. However, connectivity across groups might rely on nodes that are not the representative. But if two groups share a node, that node may not be the representative in both groups. In the star graph, if we have group1 with rep A, group2 with rep B, and they share a node C. In group1, C is connected to A (since we union C with A). In group2, C is connected to B (since we union C with B). So C connects A and B, thus A and B are connected. So the two reps become connected, and thus all nodes in group1 (connected to A) and group2 (connected to B) become connected. So connectivity is preserved. More generally, if there is a path in the original graph: user u = v0 - (group edge) - v1 - (group edge) - v2 ... vk. In the star graph, each group edge may not be directly present, but we can replace each step vi to vj (both in same group) with a two-step via the group's representative: vi - rep - vj, as long as the representative is connected to both. However, careful: what if the group's representative is not part of the group? But we chose the representative from the group members, so it's a member of that group. So for any two users a and b in the same group, there is a path a - rep - b in the star graph because we added edges from rep to a and rep to b. So the star graph's connectivity between any two users in the same group is via the rep. So the original edge can be replaced by a two-step path. Thus if there is a path in the original graph, there is a path in the star graph (maybe longer). So connectivity in original implies connectivity in star graph. So components are the same. So DSU star method works.
Thus DSU on users only is correct.
Now we need to consider: The sum of k_i ≤ 5e5, so total number of union operations is at most sum(k_i) - (number of non-zero groups) ≤ 5e5. That's fine.
Implementation nuance: We need to read input efficiently. In Python, using .split() and iter is fine.
But careful: When reading group lines, if we use for i in range(m): read k, then loop k times to read users, we need to ensure we correctly consume the integers. Using the iterator, we can read k and then read exactly k integers. That's what we do.
One more nuance: Groups may be large, but we only need to process them. For each group, we union each user with the first user. However, what if the group has many users? That's okay.
But could there be an issue where the first user is already in a large component, and we union many others with it, causing many find operations that traverse long paths? DSU with path compression handles that.
Now, we might want to use union by rank or size to keep tree shallow. Our union uses size.
Now, confirm memory: parent list of n ints, size list of n ints, comp_size list of n ints. n up to 5e5, so each list of 5e5 Python ints ~ 14 MB each, total ~42 MB. This is okay.
But we also have the list of tokens from input split. That's the biggest memory consumption. We could avoid storing all tokens by reading line by line and parsing each group individually. This would reduce memory. Since sum of k_i <= 5e5, reading line by line is feasible, and we don't need to store all tokens at once. However, Python input line by line with sys.stdin.readline() might be slower but acceptable. But we can also use sys.stdin.buffer.read() and then split, which is fast and convenient, and memory likely okay. However, given constraints total numbers up to 1e6, storing all tokens as bytes objects might use significant memory but still under limit. But to be safe, we can implement a custom fast input that yields integers without storing all tokens. But it's not necessary.
I'll go with reading all tokens using sys.stdin.buffer.read().split() because it's simplest. If memory is a concern, we can read line by line. But splitting all might be fine.
Let's approximate memory: Input size: The total number of integers is about 1e6 (including n, m, k_i, user IDs). Each integer as string in the input maybe average 3-4 characters plus spaces. So total input size ~ 4 MB. Splitting into list of bytes objects: each bytes object is a separate copy of a substring? Actually, when you call .split() on a bytes object, it returns a list of new bytes objects, each containing a copy of the substring. So memory overhead is about the size of the original data plus overhead per object. The original data is about 4 MB. Each token as a bytes object: overhead maybe 33 bytes per token. With 1e6 tokens, overhead ~33 MB. Plus the data itself copied? Actually the data is copied into new bytes objects, so another 4 MB. Total ~37 MB for tokens. DSU arrays ~42 MB, total ~79 MB. Plus other overhead like list of tokens container (list of references: 8 bytes per reference) => list of