龟兔赛跑算法 floyed判环算法

今天写线段树写到要用到这个算法的题目,简单的学习一下。

https://blog.csdn.net/javaisnotgood/article/details/89243876

https://blog.csdn.net/wall_f/article/details/8780209

https://blog.csdn.net/qq_37025443/article/details/88852318

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<set>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#include<list>
#include <queue>
#include <map>
#include <string>
#include <fstream>
using namespace std;
typedef pair<int, int> PII;
typedef long long ll;
const int N = 2018;
int mp[N];

PII cal(int s) {
	int fast = s;
	int slow = s;
	bool isCircular = true;

	do {
		if (mp[fast] == -1 || mp[mp[fast]] == -1) {
			isCircular = false;
			break;
		}

		fast = mp[mp[fast]];
		slow = mp[slow];
	} while (fast != slow);
	//确定起点
	slow = s;
	while (slow != fast) {
		slow = mp[slow];
		fast = mp[fast];
	}

	//环的长度
	int i = 0;
	do {
		slow = mp[slow];
		i++;
	} while (slow != fast);
	//printf("环的起点:%d
环的长度:%d
",slow,i);
	return make_pair(slow, i);
}

int main() {
	for (int i = 0; i < 2018; i++) {
		mp[i] = i * i % 2018;
	}
	int maxstep = 0;
	int maxcir = 0;
	for (int i = 0; i < 2018; i++) {
		PII tmp = cal(i);
		maxcir = max(tmp.second, maxcir);
		int j = 0;
		int x = i;
		while (x != tmp.first) {
			x = mp[x];
			j++;
		}
		maxstep = max(maxstep, j);
	}
	printf("最大环:%d
最大入环距离:%d
", maxcir, maxstep);
}

  

原文地址:https://www.cnblogs.com/EchoZQN/p/11321958.html