-
Notifications
You must be signed in to change notification settings - Fork 0
/
1101. The Earliest Moment When Everyone Become Friends.py
48 lines (39 loc) · 2.24 KB
/
1101. The Earliest Moment When Everyone Become Friends.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
""" There are n people in a social group labeled from 0 to n - 1. You are given an array logs where logs[i] = [timestampi, xi, yi] indicates that xi and yi will be friends at the time timestampi.
Friendship is symmetric. That means if a is friends with b, then b is friends with a. Also, person a is acquainted with a person b if a is friends with b, or a is a friend of someone acquainted with b.
Return the earliest time for which every person became acquainted with every other person. If there is no such earliest time, return -1.
Example 1:
Input: logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], n = 6
Output: 20190301
Explanation:
The first event occurs at timestamp = 20190101, and after 0 and 1 become friends, we have the following friendship groups [0,1], [2], [3], [4], [5].
The second event occurs at timestamp = 20190104, and after 3 and 4 become friends, we have the following friendship groups [0,1], [2], [3,4], [5].
The third event occurs at timestamp = 20190107, and after 2 and 3 become friends, we have the following friendship groups [0,1], [2,3,4], [5].
The fourth event occurs at timestamp = 20190211, and after 1 and 5 become friends, we have the following friendship groups [0,1,5], [2,3,4].
The fifth event occurs at timestamp = 20190224, and as 2 and 4 are already friends, nothing happens.
The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends, we all become friends. """
#dsu union直到只有一个根。
class DSU:
def __init__(self, N) -> None:
self.par = list(range(N))
self.N = N
def find(self, x):
if self.par[x] == x:
return x
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
px = self.find(x)
py = self.find(y)
if px != py:
self.N -=1
self.par[px] = py
return self.N
class Solution:
def earliestAcq(self, logs: List[List[int]], n: int) -> int:
dsu = DSU(n)
logs.sort()
for t, f1, f2 in logs:
roots = dsu.union(f1, f2)
if roots == 1:
return t
return -1