您的位置:首页 > 其它

Codeforces Round #383 (Div. 2)-C. Arpa's loud Owf and Mehrdad's evil plan

2016-12-07 13:11 561 查看
原题链接

C. Arpa's loud Owf and Mehrdad's evil plan

time limit per test
1 second

memory limit per test
256 megabytes

input
standard input

output
standard output

As you have noticed, there are lovely girls in Arpa’s land.

People in Arpa's land are numbered from 1 to n.
Everyone has exactly one crush, i-th person's crush is person with the number crushi.



Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.

The game consists of rounds. Assume person x wants to start a round, he calls crushx and
says: "Oww...wwf" (the letter w is repeated t times)
and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and
says: "Oww...wwf" (the letter w is repeated t - 1times)
and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1).
This person is called the Joon-Joon of the round. There can't be two rounds at the same time.

Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t ≥ 1)
such that for each person x, if x starts
some round and y becomes the Joon-Joon of the round, then by starting from y, x would
become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.

Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i).

Input

The first line of input contains integer n (1 ≤ n ≤ 100) —
the number of people in Arpa's land.

The second line contains n integers, i-th
of them is crushi (1 ≤ crushi ≤ n) —
the number of i-th person's crush.

Output

If there is no t satisfying the condition, print -1.
Otherwise print such smallest t.

Examples

input
4
2 3 1 4


output
3


input
4
4 4 4 4


output
-1


input
4
2 1 4 3


output
1


遍历每个人i, 用深搜找到是否存在从第i个人出发,经过次数t回到第i个人的情况,若不存在无解,若存在判断t是否为偶数,若为偶数则除以2,求出所有t的最小公倍数就是答案

#include <bits/stdc++.h>
#define MOD 1000000007
#define maxn 100005
using namespace std;
typedef long long ll;

int num[105];
int vis[105], t[105], cnt, k;
bool dfs(int j){

if(num[j] == k){
return true;
}
int h = num[j];
if(vis[h])
return false;
vis[h] = 1;
cnt++;
if(dfs(h))
return true;
return false;
}
ll gcd(ll a, ll b){
return b ? gcd(b, a % b) : a;
}
int main(){
// freopen("in.txt", "r", stdin);
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", num+i);
for(int i = 1; i <= n; i++){
memset(vis, 0, sizeof(vis));
cnt = 1;
vis[i] = 1;
k = i;
if(dfs(i) == false){
puts("-1");
return 0;
}
if(cnt&1)
t[i] = cnt;
else
t[i] = cnt / 2;
}
ll ans = t[1];
for(int i = 2; i <= n; i++){
ans = ans * t[i] / gcd((ll)ans, (ll)t[i]);
}
printf("%I64d\n", ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐