今天写线段树写到要用到这个算法的题目,简单的学习一下。
#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\n环的长度:%d\n",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\n最大入环距离:%d\n", maxcir, maxstep); }