feat: 108. 冗余连接新增python解法

This commit is contained in:
suinming
2024-09-24 14:41:38 +08:00
parent faeda4b0a2
commit 2841f59212

View File

@ -178,6 +178,45 @@ int main() {
### Python
```python
father = list()
def find(u):
if u == father[u]:
return u
else:
father[u] = find(father[u])
return father[u]
def is_same(u, v):
u = find(u)
v = find(v)
return u == v
def join(u, v):
u = find(u)
v = find(v)
if u != v:
father[u] = v
if __name__ == "__main__":
# 輸入
n = int(input())
for i in range(n + 1):
father.append(i)
# 尋找冗余邊
result = None
for i in range(n):
s, t = map(int, input().split())
if is_same(s, t):
result = str(s) + ' ' + str(t)
else:
join(s, t)
# 輸出
print(result)
```
### Go
### Rust