Niuke Practice Game 70-C.Mu Function

Topic link

answer:

It is found that there are loop nodes in the result, and the function μ(x) is a Möbius function. Then we can pre-process the value of the Mobius function, and then violently find the loop node.

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e7+10;
int prime[maxn],mu[maxn],pcnt;
bool vis[maxn];
void init() {
	mu[1]=1;
	for(int i=2;i<maxn;++i) {
		if(!vis[i]) prime[++pcnt]=i,mu[i]=-1;
		for(int j=1;i*prime[j]<maxn;j++) {
			vis[i*prime[j]]=1;
			if(i%prime[j]==0) {
				mu[i*prime[j]]=0;
				break;
			} else mu[i*prime[j]]=-mu[i];
		}
	}
	
}

signed main() {
	int test; cin>>test;
	init();
	while(test--) {
		ll n,k; scanf("%lld%lld",&n,&k);
		vector<int> v;	//存放找到循环节过程中所有的值 
		map<int,int> vis1;
		int now=n;
		while(!vis1[now]) {
			v.push_back(now);
			vis1[now]=1;
			now=now+mu[now];
		}
		int pos;
		for(int i=0;i<v.size();++i){
			if(v[i]==now) {
				pos=i;break;
			}
		}
		vector<int> v1; //存放循环节内的值 
		for(int i=pos;i<v.size();++i) v1.push_back(v[i]);
		if(k<v.size()) cout<<v[k]<<endl;
		else cout<<v1[(k-v.size())%v1.size()]<<endl;
	}
}

 

Guess you like

Origin blog.csdn.net/qq_44132777/article/details/108830937