HNOI2013 排列 (组合计数)

应用差分数列的思想

首项一共有 (n-ai) 种取值, 数列 a 一共有 m^(k-1) 种可能

ai的话,在所有可能的数列 a 中一共会出现 m^(k-1)*(k-1)个数,其中每个数出现的次数是相等的,都是 m^(k-2)*(k-1),再等差数列求个和就完啦

最后答案就是 (n-ai)*m^(k-1)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 100010; 

ll n,ans1,ans2;
int m,k,p;

ll qsm(ll i,ll po){
    ll res=1ll;
    while(po){
        if(po&1) res=res*i%p;
        i=i*i%p;
        po>>=1;
    }
    return res;
} 

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
    n=read(),k=read(),m=read(),p=read();
    n%=p,m%=p; // 很关键!! 
    ans1=n*1ll*qsm(1ll*m,1ll*k-1ll)%p;
    ans2=(1ll*m*(m+1)/2)%p*(k-1ll)%p*qsm(1ll*m,1ll*k-2ll)%p;
    printf("%lld\n",((ans1-ans2)%p+p)%p);
    return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/10342243.html