Codeforces 487C. Prefix Product Sequence 逆元+构造


题意:

对于数字n, 问是否存在1~n的一个排列 使这个排列的每一个前缀的乘积模上n 可以是0~n-1的一个排列


解析:

通过观察1肯定要在首位,n一定要在最后

除4意外的合数都没有解

其他质数构造 a[i]=i*inv[i-1] , 这样用逆元把前面每个数的影响都消除掉

C. Prefix Product Sequence
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence .

Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].

Input

The only input line contains an integer n (1 ≤ n ≤ 105).

Output

In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists.

If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n.

If there are multiple solutions, you are allowed to print any of them.

Sample test(s)
input
7
output
YES
1
4
3
6
5
2
7
input
6
output
NO
Note

For the second sample, there are no valid sequences.



/* ***********************************************
Author        :CKboss
Created Time  :2015年03月12日 星期四 19时58分14秒
File Name     :CF487C.cpp
************************************************ */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <queue>
#include <set>
#include <map>

using namespace std;

typedef long long int LL;

const int maxn=100100;

int n;
LL a[maxn],inv[maxn];

bool isprime(int x)
{
	if(x==2||x==1) return true;
	if(x%2==0) return false;
	for(int i=3;i*i<=x;i+=2) if(x%i==0) return false;
	return true;

}

void solve()
{
	inv[1]=1LL;
	for(int i=2;i<=n;i++) inv[i]=inv[n%i]*(n-n/i)%n;
	a[1]=1LL; a[n]=n;
	for(int i=2;i<n;i++) a[i]=(i*inv[i-1])%n;
	for(int i=1;i<=n;i++) printf("%I64d\n",a[i]);
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);

	scanf("%d",&n);
	if(n==4)
	{
		puts("YES"); puts("1"); puts("3"); puts("2"); puts("4"); 
		return 0;
	}
	if(isprime(n)==false) puts("NO");
	else
	{
		puts("YES");
		solve();
	}
    
    return 0;
}



你可能感兴趣的:(Codeforces 487C. Prefix Product Sequence 逆元+构造)