From 2841f59212a4f8399d53007eb01130172ce59814 Mon Sep 17 00:00:00 2001 From: suinming <0223314338aa@gmail.com> Date: Tue, 24 Sep 2024 14:41:38 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20108.=20=E5=86=97=E4=BD=99=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=96=B0=E5=A2=9Epython=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0108.冗余连接.md | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/kamacoder/0108.冗余连接.md b/problems/kamacoder/0108.冗余连接.md index 2c133782..18a86ad6 100644 --- a/problems/kamacoder/0108.冗余连接.md +++ b/problems/kamacoder/0108.冗余连接.md @@ -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