题解

https://blog.csdn.net/qq_26358509/article/details/71056436

C++代码(60%)

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b){
	return b?gcd(b,a%b):a;
}
const int N=1e4+5;
int mat[N];
bool vis[N];
int main(){
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		mat[x]=y;
	}
	ll ans=1;
	for(int i=1;i<=n;i++){
		if(vis[i]) continue;
		ll  cnt=1;
		int t=i;
		vis[t]=true;
		while(mat[t]!=i){
			cnt++;
			t=mat[t];
			vis[t]=true;
		}
		if(ans%cnt!=0){
			ans=ans/gcd(ans,cnt)*cnt;
		}
	}
	printf("%lld\n",ans);
	return 0;
}