【cf 487C】【数论+构造】【根据前缀积取模构造序列】

来源:互联网 发布:三维软件 编辑:程序博客网 时间:2024/06/08 09:22

传送门:

http://codeforces.com/problemset/problem/487/C

题意:

考虑一个序列[a1, a2, …, an]。定义其前缀产生的一个序列[a1 mod n, (a1a2) mod n, (a1a2…an mod n)]。
现在给定一个n,你需要找到一个[1, 2, …, n]的一个排列组成的序列,使得按照如上规则产生的序列是[0, 1, …,n-1]组成的一个排列。
如果不存在,输出”NO”,否则输出”YES”,然后输出这个序列。如果存在多种方案,任意输出一个。

思路:

注意到,那么一定有,也就是,否则0会出现多于1次,于是有,打表可以发现当且仅当n=1,4或者n为素数时(n-1)!不被n整除,当然这个结论是可以证明的(具体证明参考:http://codeforces.com/blog/entry/14832),考虑对这些情况进行构造,n=1就是1,n=4有一组解是1,3,2,4,

对于n是素数的情况,令,,即可,这里除法是模意义下的,也就是乘上它的乘法逆元,

那么显然有,并且同样可以证明是的一个排列。

代码:

#include <iostream>#include <stdio.h>#include <algorithm>#include <string.h>using  namespace  std;#define ll long longconst int inf=0x3f3f3f3f;const int N=1e5+10;int n, inv[N], ans[N];void inverse(int n, int p) {    inv[1] = 1;    for (int i=2; i<=n; ++i) {        inv[i] = (ll) (p - p / i) * inv[p%i] % p;    }}bool isprime(int x){    for(int i=2; i*i<=x; i++){        if(x%i == 0)return false;    }    return  true;}int  main(){    scanf("%d", &n);    if(n == 1)return 0*printf("YES\n1\n");    else if(n == 4)return 0*printf("YES\n1\n3\n2\n4\n");    else if(isprime(n)){        inverse(n, n);        puts("YES");        puts("1");        for(int i=2; i<n; i++)printf("%I64d\n", 1LL*i*inv[i-1]%n);        printf("%d\n", n);    }    else return 0*puts("NO");    return 0;}

描述:

C. Prefix Product Sequence
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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.

Examples
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.

1 0