Sekcja DSAŁatwe

Znalezienie Unii

Szczegółowy przewodnik i implementacja Python dla problemu „Union Find”.

Oświadczenie o problemie

Łatwe

Napisz funkcję detect_cycle_union_find(V, edges), która wykrywa, czy na grafie nieskierowanym składającym się z V wierzchołków i listy krawędzi edges występuje cykl, reprezentowanych jako pary (u, v) przy użyciu struktury danych Union-Find. Zwróć True, jeśli cykl istnieje, w przeciwnym razie False.

Ograniczenia
  • 1 <= V <= 1000
  • 0 <= len(edges) <= 2000

Przykłady

Example 1
Input
V = 3, edges = [(0, 1), (1, 2), (2, 0)]
Output
True
Explanation

Edge (2, 0) connects vertices 2 and 0 which are already in the same subset, detecting a cycle.

Example 2
Input
V = 3, edges = [(0, 1), (1, 2)]
Output
False
Explanation

No subset connections merge vertices already in the same subset.

Need a Hint?
Rozważ użycie struktur danych specyficznych dla wykresów, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Otwórz w Edytorze
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.