题意:对于给定的一个数列
nxt[n]
,如果现在点
i
,那么下一个点就在
思路:
首先,这是一个 n 个点
n 条边的有向图。现在要求对于从对任意点 x 出发经过
2t 次之后能够回到原点那么这个比较明显的要求这个图是必定是一个环或者多个环。
考虑环上的点数如果是奇数 Go ,那么必定要经过 t=k×Go 次回到原点才能使得条件成立
考虑环上的点数如果是偶数 Ge ,那么从这个点出发只要经过 t=(Ge)/2 次达到一个新的点,然后从这个新的点出发再经过 t=(Ge)/2 次就能回到起点。
如果图上的点不是环,那么输出 −1 ,
反之,输出 ans=lcm(G0,G1,G2,…,Gm)
所以这个问题就变成了找环的问题
#include <cstdio>
#include <string>
#include<iostream>
#include<vector>
#include <stack>
#include <queue>
#include <map>
#include <cstdlib>
#include<string.h>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef pair<int, int>pii;
typedef pair<ll, ll> pll;
typedef pair<int, ll> pil;
typedef vector<vector<ll> >vvi;
typedef vector<ll> vi;
const ll mod = 1e9 + 7;
const int MAXN = 1000;
const int MAXM = 1000;
ll gcd(ll x, ll y)
{
return y == 0 ? x : gcd(y, x%y);
}
ll lcm(ll x, ll y)
{
return x / gcd(x, y)*y;
}
int nxt[140];
int fa[140];
int vis[140];
int nowc = 0;
int flag = 1;
int main()
{
int n;
cin >> n;
ll ans = 0;
for (int i = 1; i <= n; i++)scanf("%d", &nxt[i]);
for (int i = 1; i <= n; i++)
{
if (!fa[i])
{
int now = i;
int cot = 0;
while (fa[nxt[now]] == 0)
{
fa[nxt[now]] = now;
cot++;
now = nxt[now];
}
if (now != i||fa[now]==0)
flag = 0;
else
{
if ((cot & 1) == 0)
{
if (ans == 0)ans = cot / 2;
else ans = lcm(ans, (ll)cot / 2);
}
else
{
if (ans == 0)ans = cot;
else ans = lcm(ans, (ll)cot);
}
}
}
}
if (flag)printf("%I64d\n", ans);
else printf("-1\n");
//system("pause");
}