HDU5793 A Boring Question (快速幂,逆元)

来源:互联网 发布:java中json数组遍历 编辑:程序博客网 时间:2024/05/20 17:09

题目链接

A Boring Question

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 0 Accepted Submission(s): 0

Problem Description
There are an equation.
∑0≤k1,k2,⋯km≤n∏1⩽jm(kj+1kj)%1000000007=?
We define that (kj+1kj)=kj+1!kj!(kj+1−kj)! . And (kj+1kj)=0,while kj+1kj.
You have to get the answer for each n and m that given to you.
For example,if n=1,m=3,
When k1=0,k2=0,k3=0,(k2k1)(k3k2)=1;
Whenk1=0,k2=1,k3=0,(k2k1)(k3k2)=0;
Whenk1=1,k2=0,k3=0,(k2k1)(k3k2)=0;
Whenk1=1,k2=1,k3=0,(k2k1)(k3k2)=0;
Whenk1=0,k2=0,k3=1,(k2k1)(k3k2)=1;
Whenk1=0,k2=1,k3=1,(k2k1)(k3k2)=1;
Whenk1=1,k2=0,k3=1,(k2k1)(k3k2)=0;
Whenk1=1,k2=1,k3=1,(k2k1)(k3k2)=1.
So the answer is 4.

Input
The first line of the input contains the only integer T,(1≤T≤10000)
Then T lines follow,the i-th line contains two integers n,m,(0≤n≤109,2≤m≤109)

Output
For each n and m,output the answer in a single line.

Sample Input
2
1 2
2 3

Sample Output
3
13

这题可以先打表,然后根据m相同n不同时的规律和n相同m不同时的规律找出公式,公式就是(m^(n+1)-1)/(m-1),然后用快速幂和逆元计算即可

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <set>#include <algorithm>#include <vector>using namespace std;int T;long long mod=1000000007;long long extend_gcd(long long a,long long b,long long &x,long long &y){    if(a==0&&b==0) return -1;    if(b==0)    {        x=1;        y=0;        return a;    }    long long d=extend_gcd(b,a%b,y,x);    y-=a/b*x;    return d;}long long mod_reverse(long long a,long long n){    long long x,y;    long long d=extend_gcd(a,n,x,y);    if(d==1) return (x%n+n)%n;    else return -1;}long long quickpow(long long a,long long b){    long long res=1,x=a;    while(b)    {        if(b&1)res=res*x%mod;        x=x*x%mod;        b>>=1;    }    return (res-1+mod)%mod;}int main(){    scanf("%d",&T);    long long m,n;    while(T--)    {        scanf("%I64d%I64d",&n,&m);        long long rev=mod_reverse(m-1,mod);        long long ans=rev*quickpow(m,n+1)%mod;        printf("%I64d\n",ans);    }    return 0;}
1 0