10450 | 2024-04-02 20:22:48 | 111 | Gossip Spreading | cpp17 | Accepted 100/100 | 83ms | 10508 KiB |
#include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin>>N;
vector<int>p(N);
for(int i=0;i<N;i++){
cin>>p[i];
}
vector<int>v(N),c(N),d(N+1);
int x=0;
for(int i=0;i<N;i++){
if(v[i]){
continue;
}
v[i]=++x;
int dd=1;
for(int j=p[i];j!=i;j=p[j]){
v[j]=x;
c[j]=dd++;
}
d[v[i]]=dd;
}
int Q;
cin>>Q;
while(Q--){
int a,b;
cin>>a>>b;
if(v[a]!=v[b]){
cout<<-1<<' ';
continue;
}
if(c[a]>c[b]){
swap(a,b);
}
cout<<min(c[b]-c[a],c[a]-c[b]+d[v[a]])<<' ';
}
cout<<'\n';
return 0;
}
Subtask | Sum | Test | Verdict | Time | Memory | ||
---|---|---|---|---|---|---|---|
subtask1 | 0/0 | ||||||
1 | Accepted | 3ms | 1828 KiB | ||||
2 | Accepted | 3ms | 2016 KiB | ||||
subtask2 | 30/30 | ||||||
3 | Accepted | 3ms | 2116 KiB | ||||
4 | Accepted | 3ms | 2484 KiB | ||||
5 | Accepted | 3ms | 2696 KiB | ||||
6 | Accepted | 3ms | 2908 KiB | ||||
7 | Accepted | 3ms | 3124 KiB | ||||
8 | Accepted | 3ms | 3332 KiB | ||||
9 | Accepted | 3ms | 3200 KiB | ||||
10 | Accepted | 3ms | 3252 KiB | ||||
11 | Accepted | 3ms | 3200 KiB | ||||
12 | Accepted | 3ms | 3200 KiB | ||||
subtask3 | 50/50 | ||||||
13 | Accepted | 64ms | 3856 KiB | ||||
14 | Accepted | 63ms | 3936 KiB | ||||
15 | Accepted | 63ms | 3940 KiB | ||||
16 | Accepted | 64ms | 3996 KiB | ||||
17 | Accepted | 63ms | 4028 KiB | ||||
18 | Accepted | 64ms | 4180 KiB | ||||
19 | Accepted | 64ms | 4268 KiB | ||||
20 | Accepted | 64ms | 4444 KiB | ||||
21 | Accepted | 63ms | 4452 KiB | ||||
22 | Accepted | 61ms | 4552 KiB | ||||
subtask4 | 20/20 | ||||||
23 | Accepted | 63ms | 4760 KiB | ||||
24 | Accepted | 83ms | 10232 KiB | ||||
25 | Accepted | 82ms | 10236 KiB | ||||
26 | Accepted | 83ms | 10384 KiB | ||||
27 | Accepted | 83ms | 10388 KiB | ||||
28 | Accepted | 82ms | 10376 KiB | ||||
29 | Accepted | 82ms | 10356 KiB | ||||
30 | Accepted | 79ms | 9232 KiB | ||||
31 | Accepted | 82ms | 9932 KiB | ||||
32 | Accepted | 83ms | 10508 KiB |