← 返回 snapchat 的题目列表Count Non-Friend Pairs Using Union-Find Algorithm
类型:online_judge
snapchat
Given a 2D array connections representing relationships between people, where each element is a sub-array [a, b] indicating a direct relationship between two people. Assume the people are numbered from 0 to N-1. Write a function to calculate the number of pairs who are not friends. Friendship is transitive; if A is friends with B and B is friends with C, then A and C are also friends. Implement using Union-Find algorithm and return the result.
Input:
An integer N indicating the number of people.
A 2D integer array connections, where connections[i] = [a, b] indicates a and b are directly friends.
Output:
Returns an integer representing the number of pairs who are not friends.
Example:
Input: N = 5, connections = [[0, 1], [1, 2], [3, 4]]
Output: 4
Explanation: There are 5 people, with 0, 1, and 2 being friends, and 3 and 4 being friends. In this scenario, the pairs who are not friends are (0, 3), (0, 4), (1, 3), (1, 4).
Note:
0 <= a, b < N
1 <= connections.length <= 10^4
connections[i].length == 2
Example
Input
5
[[0, 1], [1, 2], [3, 4]]