Hướng giải của Phát hiện chu trình
Nhớ rằng hướng dẫn giải này chỉ nên sử dụng khi bế tắc, và tuyệt đối không nên sao chép mã nguồn kèm theo. Hãy tôn trọng tác giả bài tập và người viết hướng dẫn giải.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.
Lời giải
Dùng thuật toán Floyd's Tortoise and Hare (slow/fast pointers). Nếu hai con trỏ gặp nhau thì có cycle.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
int main() {
int n, k; cin >> n >> k;
vector<Node> nodes;
for (int i = 0; i < n; ++i) {
int x; cin >> x;
nodes.emplace_back(x);
}
for (int i = 0; i + 1 < n; ++i)
nodes[i].next = &nodes[i + 1];
if (k >= 0) nodes.back().next = &nodes[k];
Node *slow = &nodes[0], *fast = &nodes[0];
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) { cout << "YES"; return 0; }
}
cout << "NO";
}
class Node:
def __init__(self, val):
self.data = val
self.next = None
n, k = map(int, input().split())
a = list(map(int, input().split()))
nodes = [Node(v) for v in a]
for i in range(n - 1):
nodes[i].next = nodes[i + 1]
if k >= 0:
nodes[-1].next = nodes[k]
slow = fast = nodes[0]
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
print("YES")
break
else:
print("NO")
Nhận xét