New Year and Permutation
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
A sequence a is a subsegment of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r], where l,r are two integers with 1≤l≤r≤n. This indicates the subsegment where l−1 elements from the beginning and n−r elements from the end are deleted from the sequence.
For a permutation p1,p2,…,pn, we define a framed segment as a subsegment [l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i] is always a framed segments for any i between 1 and n, inclusive.
We define the happiness of a permutation p as the number of pairs (l,r) such that 1≤l≤r≤n, and [l,r] is a framed segment. For example, the permutation [3,1,2] has happiness 5: all segments except [1,2] are framed segments.
Given integers n and m, Jongwon wants to compute the sum of happiness for all permutations of length n, modulo the prime number m. Note that there exist n! (factorial of n) different permutations of length n.
Input
The only line contains two integers n and m (1≤n≤250000, 108≤m≤109, m is prime).
Output
Print r (0≤r<m), the sum of happiness for all permutations of length n, modulo a prime number m.
一道数学题:
首先要知道只有连续的区间才有区间最大值减去区间最小值等于区间长度;
枚举区间的长度,长度为 i 的区间的取法有(n-i+1)种,这长度为 i 的区间又可以自由排列,有 i 的阶乘种,剩下的 (n-i+1)个元素(包含了这个区间本身)又可以自由排列,也是其阶乘种,所以就可以推出式子;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=200100;
const int M=1000100;
const LL mod=998244353;
LL a[300000];
int main(){
ios::sync_with_stdio(false);
int n,m;
cin>>n>>m;
a[0]=1LL;
for(int i=1;i<=n;i++){
a[i]=a[i-1]*i;
a[i]%=m;
}
LL s=0LL;
for(int i=1;i<=n;i++){//区间的长度
s+=((LL)(n-i+1)*a[i]%m*a[n-i+1]%m);
s%=m;
}
cout<<s<<endl;
return 0;
}