排列组合简单试题
题目来源:P3197 [HNOI2008] 越狱
解题思路:
既然有相同信仰的罪犯会越狱,不妨把n个房间想象为n-1个房间,其中一个房间有两个相同信仰,来大概分一下情况:4房间,2信仰,有如下情况
(11)11 / (11)12 / (11)21 / (11)22 / (22)11 / (22)12 / (22)21 / (22)22 / 8种
2(11)1 / 2(11)2 / 1(22)1 / 1(22)2 / 4种
12(11) / 21(22) / 2种
设有两个特殊信仰的房间位置为x
x之前的每个房间有m-1个选项,x之后的每个房间有m个选项
得到公式
ans=m^(n-1) + (m-1) * m ^(n-2) + (m-1) ^ 2 * m ^ (n-3) +…
不难看出是一个等比数列
合并后ans=m^n-m*(m-1) ^ (n-1)
附上ac代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll const mod=100003;
ll fast_pow(ll a,ll b){
ll res=1;
while(b){
if(b&1) res=(res*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return res;
}
int main(void){
ll n,m;cin>>m>>n;
ll ans=0;
ans=(ans+fast_pow(m,n))%mod;
ans=(ans-(m%mod)*(fast_pow(m-1,n-1)%mod));
while(ans<0) ans+=mod;
ans%=mod;
cout<<ans;
return 0;
}