Problem G. Cyclic

版权声明:小白一个,欢迎各位指错。 https://blog.csdn.net/qq_36424540/article/details/82111184

Problem Description

Count the number of cyclic permutations of length n with no continuous subsequence [i, i + 1 mod n].
Output the answer modulo 998244353.

Input

The first line of the input contains an integer T , denoting the number of test cases.
In each test case, there is a single integer n in one line, denoting the length of cyclic permutations.
1 ≤ T ≤ 20, 1 ≤ n ≤ 100000

Output

For each test case, output one line contains a single integer, denoting the answer modulo 998244353.

Sample Input

3 4 5 6

Sample Output

1 8 36

考虑容斥定理,这里主要说一下,怎样拓展

比如说 k=2的时候, 我们可能选  12 23,这种连着的,还有可能选 12 45,这种不连着的

那么首先 第一种情况 【n-(k+1)】!正常操作,

对于第二种来说,那个45又可以当做一个整体的元素来跑 ,所以就是 【n-(k+1)-1+1】!,发现还是【n-(k+1)】!,

可以推广到k,然后,就是容斥的基本操作了

#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
#define rep(i,a,b) for(int i=a;i<b;i++)

//begin
const int N=1e5+10;
const int mod=998244353;
int F[N];
LL pow_mod(LL base,int n,int mod){
	LL ans=1;
	while(n){
		if(n&1)ans=(ans*base)%mod;
		base=(base*base)%mod;
		n>>=1;
	}
	return ans%mod;
}
void init(){
    F[0]=1;
    for(int i=1;i<N;i++)F[i]=1LL*i*F[i-1]%mod;
}
//注意求逆元的时候用费马小定理前提:mod是素数
LL C(int n,int k){
     LL ans=(1LL*F[k]*F[n-k])%mod;
	 ans=pow_mod(ans,mod-2,mod);
	 return (ans*F[n])%mod;
}
LL Lucas(int n,int m){
	return m==0?1:(C(n%mod,m%mod)*Lucas(n/mod,m/mod))%mod;
}
//end

int main(){
    init();
    int T;
    scanf("%d",&T);
    while(T--){
        int n;
        scanf("%d",&n);
        LL ans=1;
        if(n&1)ans=-1;
        rep(i,0,n){
            LL flag=1;if(i&1)flag=-1;
            ans=(ans+flag*Lucas(n,i)*F[n-(i+1)]%mod+mod)%mod;
        }
        if(n==1)ans=1;
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36424540/article/details/82111184
今日推荐