104502024-04-02 20:22:48111Gossip Spreadingcpp17Accepted 100/10083ms10508 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;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1828 KiB
2Accepted3ms2016 KiB
subtask230/30
3Accepted3ms2116 KiB
4Accepted3ms2484 KiB
5Accepted3ms2696 KiB
6Accepted3ms2908 KiB
7Accepted3ms3124 KiB
8Accepted3ms3332 KiB
9Accepted3ms3200 KiB
10Accepted3ms3252 KiB
11Accepted3ms3200 KiB
12Accepted3ms3200 KiB
subtask350/50
13Accepted64ms3856 KiB
14Accepted63ms3936 KiB
15Accepted63ms3940 KiB
16Accepted64ms3996 KiB
17Accepted63ms4028 KiB
18Accepted64ms4180 KiB
19Accepted64ms4268 KiB
20Accepted64ms4444 KiB
21Accepted63ms4452 KiB
22Accepted61ms4552 KiB
subtask420/20
23Accepted63ms4760 KiB
24Accepted83ms10232 KiB
25Accepted82ms10236 KiB
26Accepted83ms10384 KiB
27Accepted83ms10388 KiB
28Accepted82ms10376 KiB
29Accepted82ms10356 KiB
30Accepted79ms9232 KiB
31Accepted82ms9932 KiB
32Accepted83ms10508 KiB