这个结构有环吗
用一个数组表示「下一个去哪」:1 2 3 4 1——最后一格指回了下标 1。运行下面这段程序:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
bool has_cycle(const vector<int>& nxt) {
int slow = 0;
int fast = 0;
while (true) {
if (nxt[fast] == -1) return false;
if (nxt[nxt[fast]] == -1) return false;
slow = nxt[slow];
fast = nxt[nxt[fast]];
if (slow == fast) return true;
}
}
int main() {
cout << boolalpha << has_cycle({1, 2, 3, 4, 1}) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)