1. 程式人生 > >luogu P3197 [HNOI2008]越獄

luogu P3197 [HNOI2008]越獄

構造長度為$n的串,給定$m種顏色,求使得相鄰兩位的顏色相同的方案數
顯然可以看出長度為$n的串染$m種顏色的總方案數為$m^{n}
-然後來考慮相鄰兩位顏色不同的方案
-對於第一位,有$m種選擇
-對於剩餘的$n-1位,有$m-1種選擇
所以相鄰兩位顏色不同的方案數就是 $m*{m-1}^{n-1}
最後就可以快樂的用快速冪求答案了

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
template<class T>void read(T &x){
    int f=0;x=0;char ch=getchar();
    while(ch<'0'||ch>'9')  {f|=(ch=='-');ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    x=f?-x:x;
}
typedef long long ll;
const int mod=100003;

ll n,m;

inline ll ksm(ll a,ll b){
    ll base=a%mod,ans=1ll;
    while(b){
        if(b&1) ans=(ans*base)%mod;
        base=(base*base)%mod;
        b>>=1;
    }
    return ans;
} 
int main(){
    read(m),read(n);
    printf("%lld\n",(ksm(m,n)-m*ksm(m-1,n-1)%mod+mod)%mod);
    return 0;
}