1. 程式人生 > >HDU 6432 Problem G. Cyclic (容斥+線性求組合數)

HDU 6432 Problem G. Cyclic (容斥+線性求組合數)

Problem G. Cyclic

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 322    Accepted Submission(s): 225


 

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

題意:

給你一個t

然後t組資料,每組資料一個n,讓你給出長度為n的迴圈排列滿足條件的方案數%998244353

條件,佇列中前一個數+1≠後一個數,並且n後面不能放1

例如n=4,只有1 4 3 2滿足

解析:

官方題解:

考慮使用容斥原理進行計數.

包含至少一個形如 $[i, i + 1]$$[n, 1]$ 這樣的子串的環排列個數是 \binom{n}{1} (n - 2)! 個;

可以推廣為包含至少 k (0 \leq k < n) 個的環排列個數是 \binom{n}{k} (n - k - 1)!,
同時注意到包含 n個的環排列個數一定是 1 個.

所以最終答案就是
(-1)^n + \sum_{k = 0}^{n - 1} (-1)^k \binom{n}{k} (n - k - 1)!

這裡長度為n的迴圈排列的方案數是(n-1)!

所以當k=4時,就是\binom{n}{k},然後再把取出來的數合併之後放回去,組成n-k個數求方案數(n-k-1)!

例如取[2,3,4,5,6] n-5+1=n-4

取[2,3,4],[6,7,8] n-6+2=n-4

取[2,3],[5,6],[8,9],[11,12] n-8+4=n-4

然後就是上面的容斥了,

最後那個包含n個的時候我具體搞不懂為什麼,下面是我根據容斥猜的。

最後k=n時,因為(n-k-1)<0,但是k=n時確實是存在一種方案的,所以還要繼續容斥,容斥係數就是(-1)^n

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;
const int MAXN = 1e5+10;

const ll MOD = 998244353;

ll jc[MAXN];

ll inv[MAXN];

void init()

{

	ll p=1;

	jc[0]=1;

	jc[1]=1;

	inv[0]=1;

	inv[1]=1;

	for(int i=2;i<MAXN;i++)

	{

		p=(p*i)%MOD;

		jc[i]=p;

		//inv[i]=inv[MOD%i]*(MOD-MOD/i)%MOD;

	}

	

	for(int i=2;i<MAXN;i++) inv[i]=inv[MOD%i]*(MOD-MOD/i)%MOD;   //O(n)求逆元

	for(int i=2;i<MAXN;i++) inv[i]=inv[i-1]*inv[i]%MOD;   //擴充套件到i!的逆元

}

inline ll C(int a, int b)    //計算C(a, b),a下,b上
{

	if(b>a) return 0;

    return jc[a] * inv[b] % MOD

        * inv[a-b]%MOD;

}

int main()
{
	int t;
	cin>>t;
	init();
	while(t--)
	{
		int n;
		cin>>n;
		ll ans=0;
		for(int i=0;i<n;i++)
		{
			ans=(i&1)?(ans-(C(n,i)*jc[n-i-1]%MOD)+MOD)%MOD:(ans+(C(n,i)*jc[n-i-1]%MOD))%MOD;
		}
		if((n&1)==0) ans++;
		else ans--;
		ans=(ans+MOD)%MOD;
		printf("%lld\n",ans);
	}
	return 0;
	

}