We need to solve the problem: given a set of friendships (undirected edges) among users, we need to output, for each user, the number of "suggested friends". Suggested friends are defined as users y such that:
- y != x
- y is not a friend of x (i.e., not directly connected)
- Among all users satisfying these two conditions, y has the maximum number of common friends with x (i.e., maximum number of users z such that x and z are friends and y and z are friends, with z != x,y)
We need for each user x, count how many such y exist (i.e., the number of non-friends with max common friends). Output all users in any order, with name and count.
Constraints: m ≤ 5000, number of edges up to 5000. Number of vertices? Not given but since each edge introduces up to 2 new vertices, maximum vertices up to 10000? But since names distinct, m up to 5000 edges, vertices could be up to 10000? Actually m pairs, each pair has two names. So total distinct names ≤ 2*m ≤ 10000. So n ≤ 10000. That's manageable.
We need to compute for each pair (x,y) not directly connected, the number of common friends. Then for each x, find the maximum common friends count among non-friends y, and count how many y achieve that maximum.
Brute force O(n^3) might be too high if n ~ 10000, but O(n^2) might be borderline if we use adjacency matrix? n^2 = 100M, maybe okay in C++ but Python might be heavy. But we have m ≤ 5000 edges, so graph is sparse. The number of non-friend pairs could be high (~n^2) if graph is dense? But m limited to 5000, so maximum possible edges among n vertices is C(n,2). For n=10000, complete graph would have ~50 million edges, but m only 5000, so graph is extremely sparse. So number of pairs of vertices (x,y) where either they are friends or not? The total pairs could be huge, but we only need to compute common friends for pairs that are not friends? Actually we need to compute for each x, for all y not friends, the common friend count. But we can compute using adjacency lists: for each x, we have its friend list (neighbors). To compute common friends count for a given pair (x,y) not friends, we can intersect their neighbor sets. However, doing that for all non-friend pairs directly could be expensive if we iterate all pairs. But note that m is small, n up to ~10000 but average degree low (2m/n). Actually average degree = 2m/n. For m=5000, n maybe up to 10000, avg degree ~1. So graph is very sparse. So for each x, its neighbor list size small. To compute common friends with y, we can for each x, iterate over all y that are two steps away via a common friend? Alternative approach: For each x, we want to find y not directly connected that have max common neighbors. We can compute for each x, for each neighbor z, for each other neighbor of z? That might produce many pairs but controlled by edges. Let's think.
Better approach: For each x, we could compute potential suggested friends by looking at friends-of-friends (2-hop neighbors) that are not directly friends. For each such y, we need to count number of common friends = number of paths of length 2 between x and y, which is exactly the number of common neighbors. We can compute for each x, by scanning its neighbor set and increment a counter for each y that is a friend of a neighbor (but not x itself and not directly friend). But careful: we need to count common neighbors exactly: if x and y share multiple common friends, we need the count. So we can for each x, initialize a map/dictionary cnt for candidate y (not friends) that counts how many common neighbors. For each neighbor z of x, for each neighbor w of z where w != x, increment cnt[w]. After processing all z, we have for each y that appears as a neighbor of a neighbor of x, the number of times we saw y, which is exactly the number of common friends (since each common friend z will contribute to increment for y from z). However, if y is already a friend of x, we should exclude them from suggestions. Also note that if y == x, we skip.
But also what about users y that are not even friends-of-friends? They would have zero common friends. They could be candidates if max common friends is 0. Indeed, if for a given x, all non-friends have 0 common friends, then all such y are suggested? That would be huge (n - 1 - deg(x)). But is that allowed? Example 2: valera has many friends, others are non-friends? In example 2: valera has friends: vanya, edik, pasha, igor (so deg=4). There are 5 users total, so non-friends for valera: none (since n=5, valera friends 4, plus himself, so no non-friends). So count 0. For other users (vanya, edik, pasha, igor), they are all friends with valera, and also each other? According to input: only edges with valera. So vanya has only valera as friend. So his non-friends: edik, pasha, igor (and maybe others? total 5, so minus himself, minus friend valera => 3 non-friends). He shares common friends? Common friends with edik? Both are friends with valera, so valera is a common friend. So each pair among these three shares exactly one common friend (valera). But they are not directly friends. So for vanya, non-friends have at least 1 common friend (actually all 3 have exactly 1). So max common friends =1, and there are 3 y with that (edik, pasha, igor). So output 3. Note that there are no other users with 0 common friends. So indeed max is 1, count=3.
But if a user has no friends-of-friends that are not already friends? That could happen if the user is connected to everyone? But since n can be larger than deg+1, there may be users not connected via any common friend. For example, consider graph: two isolated components? But problem says each user has at least one friend, so each user has at least one neighbor. However, the graph could be disconnected? Possibly, yes. For a user x in a disconnected component, there could be users in other components that have no common friends (since no path of length 2). Then for x, non-friends include all users in other components; they have 0 common friends. Meanwhile, within its component, there may be non-friends that have some common friends (maybe positive). So max common friends might be >0, but if all other non-friends have 0 and there are some with positive, then max is positive and we count only those with max. But if there are no non-friends with any common friend? That would mean that for all y not friends, they share 0 common friends. That could happen if x's component is a star: x is a leaf? Let's examine. Suppose x is a leaf, its only friend is z. Then neighbors of z include x and maybe other nodes. For y not friend: y could be a neighbor of z (other leaves) that are not directly friend of x? x is not directly connected to those leaves (except via z). So those leaves and x share common friend z (since x is friend of z and y is friend of z). So they have 1 common friend. So indeed there is positive. If component is just an edge: two nodes a and b only. Then n>=? But each user has at least one friend, so the graph with 2 nodes and 1 edge is fine. For node a, non-friends: there are no other nodes (since n=2, friend is b, non-friends none). So count 0. So only when x is in a component where there are no other nodes not directly connected but reachable via a common neighbor? Actually, if component is a triangle (complete graph of 3 nodes), each node is directly connected to the other two, so no non-friends within component. If there are other nodes in other components, they have 0 common friends. So max common friends = 0, and then all non-friends (all nodes in other components) would be suggested. That could be huge! But is that allowed? Let's check conditions: For user x, suggestion is among all network users who meet first two conditions, user y has most common friends. If max common friends is 0, then all non-friends have 0, so all are suggested. That would make output potentially large, but that's okay as we only need to output the count (which could be up to n-1 - deg(x), could be ~10000). That's fine. So our solution must handle this.
Thus we need to compute for each x, the set of non-friend y with maximum common neighbors count. The counting via friend-of-friends scanning may yield counts only for y that are at distance 2 (i.e., have at least one common neighbor). But y with 0 common neighbors won't appear in the map cnt. So we need to handle that case: if after processing all neighbors, we have some candidates; we need to find the maximum count among all y that are not friends; if the map only contains some y, but there might be other y not in map that have 0 common friends. The maximum count could be 0 if no candidate with positive count exists, OR if the maximum among positive is >0 then that's the max; but if there are candidates with positive count, then max >0, so y with 0 are not maximal. So we need to know if there exists any non-friend y with at least one common neighbor; if yes, then max >0, we ignore zeros. If there is no non-friend y with any common neighbor (i.e., all non-friends have 0 common friends), then max = 0, and all non-friends count as suggested. But careful: it's possible that there exist both positive and zero; max is positive, so zeros not counted. So we can compute for each x:
-
deg(x): number of direct friends.
-
Build map cnt for y (≠ x) that are not direct friends? Actually we can include y that are direct friends but then later exclude them. But easier: For each neighbor z of x, for each neighbor w of z, where w != x, increment cnt[w]. After processing all z, cnt[w] is number of common neighbors between x and w (since each common neighbor z contributes). However, note that if w is a direct friend of x, then w also appears as neighbor of some z? Possibly, if there is a triangle: x and w are friends, and z is a common neighbor? Actually, if w is a friend of x, then w might also be neighbor of some z? But z are friends of x, so w could be neighbor of z if the graph has triangles. Then cnt[w] will count common neighbors between x and w, including possibly w itself? No, because we skip w==x, but w can be a direct friend. However, condition for suggested friends requires that y is not a friend of x. So we must exclude those w from candidates. So after building cnt, we remove entries where w is a direct friend of x (or we can simply not consider them when computing max).
Now, after removal, if the map is empty (no candidate with at least one common neighbor) OR the maximum count among remaining is 0? Actually, cnt entries will always have count >=1 because they were incremented at least once. So they are all at least 1. So if after removal we have any entries, then max >=1, and we count those with maximum count. But we must also consider the case where there are non-friend y with zero common friends. When would that happen? It happens when the map after removal is empty, i.e., there is no y (non-friend) that shares any common neighbor with x. Then max common friends = 0, and the number of suggested friends = total non-friend users = (n - 1 - deg(x)). So we need to compute n (total number of distinct users) and deg(x).
But wait: what about users that are at distance 2 but are also direct friends? Not possible because distance 2 would imply they are not direct friends? Actually distance 2 could also be direct friend if there is an edge plus another path? But if they are direct friends, they are excluded. So our map might contain direct friends; after removing them, we are left only non-friends with common neighbors.
Thus algorithm:
-
Parse input: read m, then m lines of pairs.
-
Build a mapping from name to integer ID for easier handling.
-
Build adjacency list for each ID: list of neighbors (friends). Also store degree.
-
Compute n = number of distinct users.
-
For each user x (0..n-1):
- Initialize a dictionary (or list of size n?) for counting common friends for other users. Since n up to 10000, using a list of size n for each x might be O(n^2) memory (~100M) which is maybe borderline in Python (100M ints ~ 800MB). So we need to use more efficient method: for each x, we can use a dictionary (hash map) to count only those y that appear as neighbors of neighbors. Since the graph is sparse, sum of (degree(z) for each neighbor of x) could be high? Let's bound: For each x, sum over z in N(x) of degree(z). In worst case, if graph is dense? But m ≤ 5000, so total sum of degrees = 2m ≤ 10000. So sum_{x} sum_{z in N(x)} degree(z) is something like? We can think: For each edge (z,w), it will be counted for each x that is neighbor of z when we iterate neighbor w from z. So total operations across all x is sum over all x of sum_{z in N(x)} degree(z) = sum over all unordered edge (x,z) (since x and z are friends) of degree(z). That's like sum_{z} degree(z) * degree(z) = sum_{z} deg(z)^2. But m is 5000, max deg could be up to n-1 ~ 9999, but if one node is connected to many? But m is only 5000, so max deg <= 5000. In worst case, we could have a star: center with degree 5000, and 5000 leaves each degree 1. Then sum of deg^2 = 5000^2 + 5000 * 1^2 = 25,000,000 + 5000 ≈ 25M. That's acceptable for Python? 25M operations is okay, but if we do it for each x, it's aggregated across all x, the total work is sum_{x} deg(x)? Actually we can compute per x using neighbor iteration: for each neighbor z, we iterate through all neighbors w of z. For the star, center x (degree 5000) would have deg(x)=5000, and each neighbor z (leaf) has degree 1 (only center). So for the center, processing each z (leaf) we iterate over its neighbors (just center) and skip w==x, so no increments. So essentially zero. For a leaf x (degree 1, neighbor is center), processing center z (degree 5000): iterate over all 5000 neighbors (including leaf x). For each w != x, we will increment cnt for all other leaves (4999). So leaf x will have 1 neighbor z (center) with degree 5000, so we iterate over 5000 neighbors, skip one (itself), so 4999 increments. That's fine. So total increments across all leaves: there are 5000 leaves, each does 4999 increments, total ~25M increments (dictionary updates). That's okay in Python within time? Possibly, but we must be careful: 25M dictionary operations might be a bit heavy but should pass with m=5000 (worst-case). Actually 25M is not huge, and typical time limit maybe 2 seconds? In Python, 25M operations might be near the limit but likely okay if optimized (use list and array? But dictionary per x can be costly due to reallocation). Alternative: we could use a global array with a timestamp to avoid resetting for each x. Since n ≤ 10000, we could allocate an integer array count of size n, and for each x, we mark visited? But we need to reset after each x, which would be O(n^2) resetting (1000010000 = 100M) which is worse. Better: we can use a dictionary or use a list and only clear entries we set. With dictionary, per x, we add entries for y with count of common neighbors. That's O(k) where k is number of candidate y's. In worst-case star, for leaf, candidate y = all other leaves (4999), so dictionary size ~5000. So across all leaves (5000), total dictionary entries created = 5000 * 5000 ≈ 25M inserts? Actually each leaf creates its own dictionary and inserts 4999 entries. So total insert operations 5000*4999 ≈ 25M, each insert O(1) average. So total operations ~25M, which is okay.
But note: if graph is dense? m limited to 5000, so can't be dense. So worst-case total increments ~ sum_{x} sum_{z in N(x)} (deg(z)-1 maybe) = we can compute. Actually each edge (z,w) with z != w contributes to how many x? For each x that is neighbor of z and x != w, we will increment cnt[w] when processing x and neighbor z. That's x such that (x,z) is an edge and x != w. That's exactly for each edge (z,w), for each other neighbor x of z (x != w), we count. So total increments = sum_{(z,w) in E} (deg(z)-1) since for each edge (z,w), for each other neighbor x of z, we count an increment for x's cnt[w]. So sum over directed edges? Let's consider undirected: each unordered edge (z,w) will be considered twice? Actually in algorithm: For each x, for each neighbor z, for each neighbor w of z (w != x). So for each ordered pair (x,z) where x and z are friends, and each w neighbor of z with w != x. That is equivalent to for each edge (z,w) and each x such that x is neighbor of z and x != w. So total increments = sum_{z} deg(z) * (deg(z)-1) because for each vertex z, there are deg(z) choices for x (neighbors) and for each x, we iterate over all other neighbors w of z (deg(z)-1). So total increments = sum_{z} deg(z)(deg(z)-1). This equals sum deg(z)^2 - sum deg(z). Sum deg(z) = 2m ≤ 10000. So total increments ≤ max possible sum deg(z)^2 given 2m total sum. For fixed sum S = 2m, sum of squares is maximized when distribution is skewed: one vertex has degree S and others degree 1? But degree cannot exceed n-1; but with m=5000, S=10000. In a star, one vertex degree = 5000? Actually with m=5000, S=10000, star: center degree = 5000, leaves 5000 each degree 1. Then sum deg^2 = 5000^2 + 50001^2 = 25,000,000 + 5000 = 25,005,000. Subtract sum deg = 10000 gives ~24,995,000 increments. That's the worst-case? Let's check if we can have a vertex degree 10000? That would require 10000 edges but m=5000, so max degree ≤ 5000 (since each edge contributes 1 to degree of two vertices, total degree sum 10000; a single vertex can have at most 5000 edges if all edges incident to it, then remaining 5000 endpoints each degree 1. So max degree = 5000. So sum deg^2 maximum is indeed when one vertex has degree 5000, rest 5000 vertices degree 1: sum deg^2 = 25,000,000 + 5000 = 25,005,000. That's about 25e6 increments. That's okay. But also there could be scenario with two high-degree vertices sharing edges? For sum of squares, given sum fixed, the maximum sum squares is when distribution is as unequal as possible. So star seems max. So total increments ≤ about 25 million. That's acceptable in Python.
But we also need to consider that each increment is a dictionary operation for a specific x. However, we need for each x a separate dictionary. So overall memory: we'll create n dictionaries, but each dictionary might hold up to O(n) entries for that x, but in worst-case total entries across all x is sum of candidate set sizes. For star: center has no candidates (since all others are leaves but are they non-friends? Center is connected to all leaves, so all leaves are friends, thus no non-friend? Actually center's friends are all leaves, so all other nodes are friends, so non-friends none? So center's candidate set empty. Leaves: each leaf's candidate set is all other leaves (4999). So total entries = 5000*4999 ≈ 25M entries across all dictionaries. But each entry is a key-value pair (int, int). That's a lot of memory (25M dict entries). Each dict entry overhead is large (~72 bytes maybe), so 25M * 72 = 1.8 GB, which is too much. So we cannot store per-x dictionaries simultaneously; we must process each x independently and discard after computing answer, i.e., we can compute for each x sequentially, without storing all dictionaries at once. That's fine: we can iterate over each vertex x, compute its suggested friends count using a local dictionary (or maybe using a list with sentinel for speed), output result, then discard it. So memory will be O(max candidate size for a single x) which at most n (10000) for a leaf in star: 4999 entries, which is fine. So we can do per x loop.
Thus algorithm steps:
- Parse input, assign IDs to names (using dict). Build adjacency list: list of sets or lists? We need to efficiently check direct friendship when we filter out friends. For each x, we can have a set of neighbors (maybe using Python set) for O(1) membership checks. But building set for each vertex might be memory heavy? n up to 10000, each set overhead maybe okay. Or we can use list and later convert to set or use boolean array for membership per x? But we need to check if a candidate y is friend of x. Could precompute adjacency matrix as bitset? Not necessary. Since we have adjacency list, we can store neighbors as list and also maybe a boolean array for each x? But we can just have a set for each vertex to test membership quickly. Since m=5000, total edges small, total neighbor entries = 2m = 10000, so total set overhead: 10000 entries across all sets? Actually each neighbor appears in two adjacency lists, so total set entries = 2m = 10000. So each vertex's set might contain many neighbors only if it's high degree; the center in star has 5000 neighbors, so its set contains 5000 entries. That's okay memory wise (5000 ints). So using set is fine.
Alternatively, we can store as list and later for filtering we can create a set for x (maybe convert list to set for membership test) but we can also just use a boolean visited array for friends: for each x, we can mark its friends in a global boolean array? But we need per x, and we can reuse a global array with timestamps to test if y is friend of x. That might be faster: we can have a global list isfriend of length n, but we need to reinitialize for each x. Instead we could have a set per x, but building set from list each time might cost O(deg(x)), which is fine.
Simplify: store adjacency as list of lists (neighbors). For each x, we have its list adj[x]. For checking direct friend, we could create a set friends_set = set(adj[x]). Since we need to check for each candidate y whether y is in that set. Since candidate y count may be up to O(n), doing a set lookup is O(1) average.
Thus per x:
-
friends_set = set(adj[x]) (or we could just use a boolean array of length n marking friend indices, but building that array per x would be O(n) to clear, which is too heavy if we do per x. Better to use set because its construction is O(deg(x)), which is fine.)
-
Initialize a dictionary cnt (defaultdict(int) or ordinary dict) to count common friends for candidate y.
-
For each neighbor z in adj[x]:
For each neighbor w of z:
if w != x:
cnt[w] += 1
-
After that, we have counts for w, which include friends and non-friends. We need to filter out w that are in friends_set (direct friends) or w == x (already skipped). Also we should exclude w == x but we already skipped.
-
Then we need to compute the maximum count among remaining y.
-
If there are no remaining y (i.e., no non-friend y with at least one common friend), then max_common = 0, and suggested_count = total_non_friends = n - 1 - deg(x). Because all non-friends have 0 common friends, so all are suggested.
-
Else, let maxc = max(cnt.values()). Then count how many y have cnt[y] == maxc (and y not friend). That's suggested_count.
-
Record (name, suggested_count) for output later.
We need to be careful: The candidate y might also be x? We skip w == x in inner loop, so not included. Also we should ensure we don't count y that are direct friends.
Now, is it possible that some non-friend y appears in cnt but with count 0? No because cnt is only incremented, so count >=1 if present.
Edge Cases:
-
Self loops? Not allowed.
-
Duplicate edges? Not allowed.
-
Users with no non-friends: deg(x) = n-1, so total_non_friends = 0. Then we don't need to compute anything; answer is 0. Our algorithm: after building cnt, we will likely have some candidates (since all other vertices are friends, they appear in cnt but we filter them out). So after filtering out friends, remaining will be empty. Then we go to case of no remaining, and compute total_non_friends = n-1 - deg(x) = 0, which is correct.
-
If there are non-friends but none share any common neighbor, then remaining after filter empty, we compute total_non_friends. That includes all non-friends. That matches earlier reasoning.
-
If there are non-friends and some share common neighbors, but maxc could be less than some? Actually we compute max among those present; they are at least 1, so maxc >=1, and we count those with that max. That excludes those with 0 because they are not in cnt.
But wait: What about the possibility that there is a non-friend y that shares some common neighbors, but also there are non-friends with 0? The max will be >0, so only those with positive count and max will be counted. That's correct.
Thus algorithm seems correct.
Now we need to compute n. We'll have mapping name_to_id. While reading edges, assign new IDs to names as encountered. Build adjacency lists: for each edge (a,b), add b to adj[a] and a to adj[b].
After reading all, we have list names in order (id_to_name). Then we compute for each id from 0 to n-1, do the above.
Complexities:
-
For each x, we iterate over neighbors z, and for each z over its neighbors w. The total work across all x is sum deg(z)^2? Actually sum over x deg(x)*something? But per x it's sum_{z in adj[x]} deg(z). So total time across all x = sum_{x} sum_{z in adj[x]} deg(z) = sum_{z} deg(z) * deg(z) = sum deg(z)^2. That's at most ~25 million, as argued. That's acceptable.
-
For each x, we also construct a set of its friends. That's O(deg(x)) time, which is negligible.
-
Then we iterate over cnt dictionary to find max and count, size up to maybe n. In worst-case for a leaf in star, cnt size = n-2? Actually leaf's candidate y are all other leaves (n-2? Actually total vertices n = 5001? star: center + 5000 leaves => n=5001. For leaf x: friends_set includes center only. cnt built from neighbor center: iterate over all neighbors of center (all leaves + maybe center? but center is neighbor of itself? no), for each w in adj[center] (all leaves and also maybe x? Actually center's neighbors are all leaves, so adj[center] contains 5000 leaves. When x is leaf, neighbor z = center, we iterate w over adj[center], which includes all leaves. For w != x, we increment cnt for all other leaves. So cnt size = 4999 (all leaves except x). So about n). So scanning cnt dictionary for max is O(n) per x. Summed over all x, that could be O(n^2) = 100M in worst-case (50005000 = 25M? Actually n up to 10000, but with star n=5001, each leaf does O(n) scanning: 5000 * 5000 = 25M. That's okay. However in worst-case n=10000, but m=5000 restricts n maybe up to 10000. Could we have scenario where many vertices have large candidate sets? Let's see the worst-case for sum of cnt sizes. For each unordered pair (x, y) that are not directly connected but share at least one common neighbor, it will be counted in cnt for x (and also for y). So total entries across all x = number of ordered pairs (x, y) with x != y, not friends, and have at least one common neighbor. This could be as high as? For a complete bipartite graph? Let's think: m=5000, we want maximize number of such ordered pairs. Consider a dense graph? But m limited to 5000, so edges are limited. Maximum number of ordered pairs (x,y) with common neighbor? Could be O(n^2) but can it reach n^2? For a graph that is a complete graph minus a matching? Actually to have many pairs with common neighbor, you want many vertices to be connected through a central hub. The star gives: For leaf x, candidate y are all other leaves, giving O(n^2) ordered pairs? For n vertices, leaves count = n-1, each leaf has O(n) candidates, so total entries = (n-1)(n-2) ≈ n^2. With n up to ~10000, that would be 100 million entries. But is that possible with m=5000? Star: center connected to all leaves, number of edges = n-1. So m = n-1 ≤ 5000, so n ≤ 5001. So maximum n is 5001. So total entries across all x for star: leaves each have ~5000 entries, total ≈ 50005000 = 25 million. That's okay. If we have two hubs? Suppose we have two hubs each connected to many leaves, but edges limited. The worst-case total entries may be still around sum deg(z)^2, which we already bounded by about 25 million. Because each cnt entry corresponds to some increment from a neighbor of a neighbor. Actually the total number of cnt entries across all x is not exactly sum deg(z)^2; it's the number of distinct y per x that get incremented at least once. But each increment operation results in a dictionary entry; if we use dict, we will be inserting many duplicate keys. But the number of distinct (x,y) pairs with at least one common neighbor is at most sum deg(z)^2? Let's derive: For each vertex z, consider all ordered pairs (x,y) such that x and y are distinct neighbors of z? But that counts pairs where x and y both neighbors of z; but this pair will be counted in x's cnt when we process neighbor z? Actually when x's neighbor is z, and we iterate over w = y, we increment cnt[y] for x. So each unordered neighbor pair (x,y) of z (x != y) contributes one increment for x (and later when processing y, also for y). So total increments = sum_{z} deg(z)(deg(z)-1). That's number of ordered pairs (x,y) where x and y are distinct neighbors of z, and we count as increment for x. So total increments = about sum deg(z)^2. The number of distinct (x,y) pairs that get incremented at least once could be less than total increments because same (x,y) pair could be counted multiple times if they have multiple common neighbors. For each common neighbor z, we get an increment. So number of distinct (x,y) pairs (with at least one common neighbor) is at most total increments, but possibly much smaller if many multiple common neighbors. However, the dictionary per x will store each y only once, with count being the number of increments. So the total number of dictionary entries across all x is the number of distinct (x,y) pairs that have at least one common neighbor. This is at most total increments, and in worst-case (star) each pair appears exactly once (since only one common neighbor), so it's equal to sum deg(z)(deg(center)-1) + leaves contribute nothing because deg(leaf)=1 gives 0. For star with center degree d, sum = d*(d-1). With d=5000, that's ~25e6. That matches our earlier estimate. So total entries across all dictionaries processed sequentially (not simultaneously) is about 25 million. Each entry insertion and update in dict takes some time, but 25 million operations is okay (maybe around 1-2 seconds in Python if optimized). However, note that for each x we also need to iterate over cnt to find max, which adds O(size of cnt). In star, each leaf's cnt size = d-1 ≈ 5000, total over all leaves = d*(d-1) = 25e6 operations again. So total work maybe ~50 million dict operations + loops. This is acceptable.
But we must be careful about the case where there are many users but low degrees? Then the per-x loops are small.
Thus the algorithm is feasible.
Now we need to implement: We'll parse input lines; we may have to read up to 5000 lines; straightforward.
Implementation Steps:
- Use sys.stdin.read().splitlines() for fast reading.
- Initialize name_to_id = {}
- adj = [] (list of list) but we need to assign IDs on the fly. We'll use dictionaries to map names to index, and list for adjacency as we add.
But we don't know number of vertices beforehand. So we can do:
name_to_id = {}
adj = [] # adjacency list as list of lists
edges = [] # store pairs to add later? Actually we can add directly after mapping.
for each line in lines[1:]:
a, b = line.split()
if a not in name_to_id:
name_to_id[a] = len(adj)
adj.append([])
if b not in name_to_id:
name_to_id[b] = len(adj)
adj.append([])
ida = name_to_id[a]
idb = name_to_id[b]
adj[ida].append(idb)
adj[idb].append(ida)
But careful: we need to ensure we don't add duplicate edges? Problem says each pair appears only once; but we could still have duplicate? Not. So fine.
After building adj, n = len(adj). We'll also store names: id_to_name = list of names (maybe we can invert dict or store separate list). While building, we can also store a list names, but we need mapping from name to id, and later output names. So we can maintain a list names = [] and when adding new id, append name.
if a not in name_to_id:
name_to_id[a] = len(names)
names.append(a)
adj.append([])
Then after building, we have adjacency list. Each adjacency list may contain duplicates if input has duplicate edges, but not. We could also convert each to set later for fast membership test? But we can just leave as list and for membership, we can construct a set from it per x. That's fine.
Now we need to compute result for each id.
Pseudo:
results = []
for x in range(n):
friends = set(adj[x])
deg = len(adj[x])
# If deg == n-1: then no non-friends, answer 0 (we can skip computation)
# But we still need to compute quickly; we could just output 0.
# But we can still do computation; but to save time, we can check:
if deg == n-1:
results.append((names[x], 0))
continue
cnt = {}
# For each neighbor z of x
for z in adj[x]:
for w in adj[z]:
if w != x:
# increment cnt[w]
cnt[w] = cnt.get(w, 0) + 1
# Remove friends (including x? Already w != x)
# Determine max among y not in friends
maxc = -1
count = 0
for y, c in cnt.items():
if y not in friends: # not direct friend
if c > maxc:
maxc = c
count = 1
elif c == maxc:
count += 1
if maxc == -1: # no non-friend with common neighbor
# all non-friends have 0 common friends
suggested = n - 1 - deg
else:
suggested = count
results.append((names[x], suggested))
But we must be careful: The condition "user y is a suggested friend for user x" includes requirement that y is not a friend of x, and x≠y. We have ensured y not in friends. Also we skip w==x. So good.
Edge Cases:
-
Users with no non-friends: deg == n-1, then we output 0. Our code: if deg == n-1, we set answer 0 directly. Actually we could also rely on loop: friends set includes all others; cnt may contain entries but they will be filtered out; after filtering, maxc stays -1 and we compute suggested = n-1 - deg = 0, which is correct. But we can skip unnecessary work. However, for star center, deg = 5000, n-1 = 5000, so it's full. So skipping saves time.
-
What about users with no non-friends but also no common neighbors? Actually if deg == n-1, no non-friends at all, answer 0; correct.
-
What about users with non-friends but no common neighbors? Then cnt may have only entries that are friends? Could there be any entries that are non-friends? If there is no common neighbor between x and any non-friend, then cnt might have some entries but they are all friends? Possibly. For example, consider graph with two components: component A: a-b (edge). Component B: c-d (edge). For a: friends = {b}. Its neighbor z = b, adj[b] = {a}. When iterating w in adj[b], only w=a, which is x, so skip. So cnt empty. So maxc = -1, suggested = n-1 - deg = total other vertices - friends: n=4, deg=1, so non-friends = 2 (c and d). So answer 2. That's correct because both have 0 common friends.
-
Another scenario: graph: triangle a,b,c all connected. For a: friends = {b,c}. deg=2, n=3. Non-friends none (since n-1=2). So answer 0. Our code: deg == n-1? Yes, 2==2, answer 0.
-
Another scenario: graph: a-b, b-c, so line of three. For a: friends = {b}. neighbor z=b, adj[b] = {a,c}. iterate w: for w=a skip, w=c -> cnt[c]=1. cnt contains c. c not in friends, so maxc=1, count=1. Non-friends: c? also maybe others? n=3, non-friends = total non-friends = 1 (c). So answer = 1. That matches: a and c share common friend b.
-
Check example 1:
Input:
5
Mike Gerald
Kate Mike
Kate Tank
Gerald Tank
Gerald David
We have 5 users: Mike, Gerald, Kate, Tank, David. Edges: Mike-Gerald, Mike-Kate? Actually second line: Kate Mike -> yes. Kate Tank, Gerald Tank, Gerald David.
Let's compute.
Our algorithm should produce outputs as given.
Now test algorithm on example 1 manually.
Works.
Now consider example 2:
4 edges among 5 users, valera connected to everyone else? Actually edges: valera vanya, valera edik, valera pasha, valera igor. So valera degree 4, others degree 1. n=5. For valera: deg=4, n-1=4, so no non-friends, answer 0.
For vanya: friends = {valera}. neighbor = valera. adj[valera] = [vanya, edik, pasha, igor]. iterate w: for w=vanya skip, for w=edik -> cnt[edik]=1, w=pasha cnt[pasha]=1, w=igor cnt[igor]=1. cnt contains edik,pasha,igor. They are not friends (vanya only friend is valera), so maxc=1, count=3. non-friends? n=5, deg=1, non-friends total =3. cnt size=3, so suggested=3. correct.
So algorithm works.
Now need to consider correctness when there are multiple common neighbors. For a pair (x,y) that have multiple common friends, cnt[y] will be incremented for each common friend. So count is accurate.
Now about performance: For each x, building friends set = set(adj[x]) takes O(deg(x)). That's fine.
But we need to iterate over neighbors of neighbors. In inner loop, we access adj[z] for each z. Could use list for adjacency.
One optimization: For each x, we can precompute friends set or use a boolean array with sentinel to test membership quickly, but using set is okay.
Potential Pitfall: The dictionary cnt may contain y that are direct friends; we filter using set membership. That set may be large (for high-degree nodes) but that's fine.
Now need to output results. We have to print n (number of users) and then for each user, name and suggested count. The order can be any, but we must output each user exactly once. We'll iterate over ids in order of mapping, and output accordingly.
Now we must ensure we handle case when n is up to maybe 10000, and m=5000, but the algorithm per x may be heavy but okay.
But one more nuance: For x, if there are many candidates, the dictionary might be large. However, we can further reduce overhead by using collections.Counter? Not needed.
But we need to be careful about the loop: for each neighbor z, for each w in adj[z]. If we use for w in adj[z]: and then if w != x: cnt[w] = cnt.get(w,0)+1, that's fine.
But what about the case where there are multiple common neighbors: We'll increment cnt[w] multiple times if there are multiple z that are common neighbors? Actually yes: If y and x have two common friends, then for each common friend z (neighbor of x), we'll see w=y from each such z. So cnt[y] gets incremented accordingly.
Now, about case where x has high degree and we process many neighbors z with large adjacency. That's fine.
Now we need to ensure we don't double count y that is both neighbor of multiple z but also maybe neighbor of x? That's filtered.
Now think about memory: storing adjacency as list of lists: total entries = 2*m ≤ 10000, so fine.
Now consider potential issue: We need to treat names case-sensitively? Yes, names can be uppercase and lowercase, distinct. So we use string as is.
Now test on examples.
Let's simulate quickly with code mental.
Now think about correctness of max common count being zero case. Our approach: if after filtering, maxc == -1, we set suggested = n-1 - deg. But is it possible that after filtering we have some entries but all are friends (i.e., all cnt keys are friends)? Then maxc would be computed only on those that are not friends, but if all are friends, then after filtering none remain, so maxc stays -1, and we go to zero case. That's correct because then there is no non-friend with common neighbor, so all non-friends have 0 common friends. So suggested = total non-friends.
But what about a situation where there is at least one non-friend with common neighbor, but the maxc among them is 0? That cannot happen because if a non-friend appears in cnt, its count is at least 1. So maxc >= 1. So we're good.
Now edge case: n=1? But problem says each user has at least one friend, and m≥1, so there must be at least two users. So n>=2.
Now about reading input: m lines. But note: The first line is m. But there may be trailing spaces? Use split.
Now output: first line n, then each line "name d". The order can be any; we'll output in order of id.
Now check time: For star with n=5001, for each leaf we iterate through center's adjacency list of size 5000. So per leaf, inner loop does 5000 iterations, of which 4999 increments. That's 25 million increments. For each increment we do a dict get+set. That's maybe 25 million dict operations. Python can handle maybe 50 million simple ops within a couple seconds? Probably okay if optimized. But we can micro-opt: Use local variable for cnt, use cnt = {} and then:
for z in adj[x]:
for w in adj[z]:
if w != x:
cnt[w] = cnt.get(w, 0) + 1
Alternative: Use from collections import defaultdict and cnt = defaultdict(int), then cnt[w] += 1 may be slightly faster? defaultdict(int) may be a bit faster than manual get, because cnt[w] += 1 does two lookups? Actually defaultdict's getitem returns default if missing, then setitem. It's generally faster for increments. But we can test. I'd use defaultdict(int). Then:
cnt = defaultdict(int)
for z in adj[x]:
for w in adj[z]:
if w != x:
cnt[w] += 1
Then after loop, we need to compute max among those not in friends. We'll iterate over items, checking if y not in friends.
But note: For each leaf, the friends set size is 1 (center). Checking if y not in friends for each y (4999 times) is O(1) per check. Good.
Now about constructing friends set: friends = set(adj[x]). That's O(deg). Could also use a boolean list of length n for each x, but that would be O(n) reset each time, which is heavy. So set is fine.
Now, for the case where n is large but deg small, constructing set is cheap.
One more optimization: if deg(x) == 0? Not possible because each user has at least one friend. But maybe? The problem says each user has at least one friend; that is guaranteed.
Now, what about duplicates in adjacency? Not, but we can ensure adjacency lists are unique. In building, we could add both directions, but there is no duplicate edge input, so no duplicates.
Now we need to be careful about the dictionary cnt might contain y that are x? We skip w != x, so no.
Now test with a tricky case: Graph with multiple components, some isolated? Actually each user must have at least one friend, so no isolated vertices. So graph is at least each vertex degree >=1. But components may be disconnected. Our algorithm still works, because for a vertex in one component, its neighbors are only within component. The cnt will only contain vertices reachable via length-2 paths, which are within the same component (since any common neighbor must be in same component). Non-friends from other components won't appear in cnt. Then for that vertex, after filtering, if there are no non-friends with common neighbor, we compute suggested = total non-friends (including those in other components). That's correct because they have 0 common friends. So that matches condition.
Now think about a scenario where a vertex has both non-friends within its component (some with common neighbor) and non-friends outside component (0 common). The max among non-friends with common neighbor is >=1, so we count only those with that max, not the ones with 0. So correct.
Now what about if there are non-friends within component but with 0 common friends? Could that happen? Yes, if they are in same component but distance >2? For example, in a path of length 3: a-b-c-d. For a, friends: b. Non-friends: c, d. Common friends with c? a and c share b? Actually a and c: a is friend with b, c is friend with b? c is friend of b? Yes, because edge b-c? Actually path: a-b, b-c, c-d. So a's friends: b. b's neighbors: a and c. So c is a neighbor of b, so when processing z=b, w includes c. So cnt[c] becomes 1. So c has common friend b. For d: a's neighbor b's neighbors are a and c, not d. So d does not appear in cnt. So after filtering, c appears (count=1) and is non-friend, so maxc=1, count=1. d is not in cnt, so considered 0 common friends, but max is 1, so d not suggested. So answer for a: suggested friends = 1 (c). That matches expectation: a and d have no common friends, c has one.
Now think about another scenario: In a component, there may be a vertex y that is not connected by any common neighbor with x, but they are in same component. Our algorithm will not include y in cnt, so its count is 0. So that's fine.
Now about efficiency: The inner loops might be okay. But we might want to skip adding w if w is x or if w is direct friend? But we need to count even if w is direct friend? Actually we want count for all w, even if w is direct friend, because we need to know count? But we will later filter them out. However, counting them might be unnecessary work, but it's easier to include and filter. However, if we skip incrementing for w that are direct friends, we could reduce work. But checking if w is a direct friend for each w might be extra overhead. Since direct friends are few relative to all w? In star leaf, direct friend is just the center, but we already skip w == x? Actually for leaf, direct friend is center, which we will encounter many times? In leaf x, neighbor z = center. When iterating w over adj[center], we will encounter all leaves including x (skipped) and also other leaves. The center is also a neighbor but we only loop over w from adj[z], and z is center, so w includes all leaves. The direct friend of x is center, but center is z, not w? Wait: w are neighbors of z. For leaf x, its only direct friend is center. In the iteration over neighbors of center, w includes all leaves (including x itself). But we skip w == x, but we also encounter other w that are not direct friends (the other leaves). The center is not w because w is neighbor of center, not center itself. So we don't increment cnt for the center. So we don't have to worry about skipping direct friends because direct friends may appear as w only if there is a triangle: if x and y are friends, and there is some z that is neighbor of x and also neighbor of y? That would make y appear as w when iterating over z (if z is common neighbor). For example, triangle: x-y and x-z and y-z. Then for x, neighbor z, when iterating w over adj[z], we see y (since y neighbor of z). y is a direct friend of x. So we will increment cnt[y] even though y is direct friend. That's okay; we filter later. However, we could skip increment if w in friends_set? But that would require checking membership each time. That could reduce increments for triangles, but triangles are not too many (graph sparse). Probably not worth. So keep as is.
Now we need to consider if any w appears multiple times from different z. That's fine.
Now, after we have cnt, we need to compute max among non-friends. We could also compute while iterating, but it's fine after.
One more nuance: The dictionary may contain keys that are not in friends_set; we need max count among them. However, it's possible that after filtering, the maximum count is 0 if no such keys. So we need to detect if there is at least one non-friend key. Our approach uses maxc = -1 and update only when we find non-friend. Then after loop, if maxc == -1, we go to zero case. This works.
But careful: What if there are non-friend keys but all have count 0? That can't happen because any key in cnt got at least one increment. So fine.
Now we need to ensure that we treat all y that are not friends equally, including those with 0 common friends, when maxc==-1. In that case, all non-friends have 0, so number of suggested friends is total_non_friends. However, there might also be some y that are not in cnt but are also non-friends; but we must count all. So total_non_friends is n - 1 - deg(x). That includes all y not friends, regardless of whether they appear in cnt or not. So that's correct.
But we must double-check: Could there be a non-friend y that appears in cnt but with count 0? That would be if we added it but never incremented? Not possible; we only add via increments.
So overall algorithm stands.
Now complexity again: For each x, we may iterate over many w. But we could also compute common counts using intersections of neighbor sets? That could be more efficient if degrees are small, but our method is straightforward.
Potential optimization: For each x, we can store its neighbors in a set for O(1) membership. And we can also compute cnt using a dictionary but we might use list of size n with sentinel to avoid dictionary overhead? However, resetting list each time would be O(n) per x, which is O(n^2) = up to 100M, maybe okay? 100M operations of integer assignment might be okay, but memory of list of length n (10000) per x? We would need a fresh list or reuse one list and reset using a timestamp array technique. That could be more efficient: we have a global array cnt of length n initialized to 0, and a global array used to mark which indices have been modified for this x, so we can iterate over used to compute max and then reset only those. But we need to differentiate between counts from previous x. We can use a global vis array of ints, with a version counter per x. Or we can use cnt = [0]*n and after processing, for each y that we touched, we record its count, then later reset those to 0. Since total touches