Codeforces Round #663 (Div. 2) C. Cyclic Permutations(组合数学)

题目链接

思路:

减后再增必成环,列出所有情况,然后再减去只先增一次再减一次的情况和只递增和只递减的情况即可。

代码:

#include<bits/stdc++.h>
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int mod=1e9+7;
const int N=1e6+5;
using namespace std;
int quick(int a,int b)
{
	int sum=1;
	while(b)
    {
		if(b&1)
        {
			sum=(sum*a)%mod;
			b--;
		}
		b/=2;
		a=a*a%mod;
	}
	return sum;
}
int n,a[N],b[N],sum=0;
signed main()
{
    IOS;
    cin>>n;
    a[1]=1;
    a[0]=1;
    b[0]=1;
    for(int i=1;i<=n;i++)
    {
        a[i]=(a[i-1]*i)%mod;
        b[i]=quick(a[i],mod-2);
    }
    for(int i=1;i<n-1;i++)
    {
        sum=(sum+(a[n-1]*b[i])%mod*b[n-1-i])%mod;
    }
    cout<<(a[n]+mod-2-sum)%mod<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ACkingdom/article/details/107903538