NC208333. 牛牛和牛可乐的赌约
描述
输入描述
有多组输入样例,第一行为样例组数
接下来t行每行有一个整数n和m,分别表示骰子的面数和牛牛的投掷次数
输出描述
输出t行,每行输出为分数p/q mod 1e9+7的形式
示例1
输入:
1 2 1
输出:
500000004
C++ 解法, 执行用时: 548ms, 内存消耗: 10016K, 提交时间: 2023-08-12 10:10:45
#include <iostream> #include <cstring> #include <algorithm> #define int long long using namespace std; const int p = 1e9 + 7; int n, m; inline void read(int &x) { // 返回类型必须为void,否则竞赛中Linux测评会报错,Windows没事 x = 0; short flag = 1; char c = getchar(); while(c < '0' || c > '9'){ // 此处如果只用if的话容易在数据不规范时出错,特别是cin和read混用 if(c == '-')flag = -1; c = getchar(); } while(c >= '0' && c <= '9') { x = (x << 3) + (x << 1) + (c ^ 48); // 48这个数字恰好往后10个数都可以使用位运算,可以写成二进制证明;位运算能用当然更好 c = getchar(); } x *= flag; } int qmi(int a, int b, int p) { int res = 1; while(b) { if(b & 1) res = res * a % p; b >>= 1; a = a * a % p; } return res % p; } signed main() { int T; read(T); while( T -- ) { read(n); read(m); int pown = qmi(n, m, p); int inv = qmi(pown, p - 2, p); int ans = ((pown - 1) * inv) % p; printf("%lld\n", ans); } return 0; }
Java 解法, 执行用时: 2290ms, 内存消耗: 28036K, 提交时间: 2023-08-12 10:10:00
import java.io.*; import java.math.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { int t=nextInt(); long mod=1000000007; while(t-->0) { int n=nextInt(),m=nextInt(); long res=qpow(n,m,mod); long ans=qpow(res,mod-2,mod); out.println((1-ans+mod)%mod); } out.flush(); } public static long qpow(long a,long b,long mod) { long res=1; while(b>0) { if(b%2==1)res=(res*a)%mod; b>>=1; a=(a*a)%mod; } return res; } static Scanner scan =new Scanner(System.in); static PrintWriter out =new PrintWriter(new OutputStreamWriter(System.out)); static StreamTokenizer in =new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); public static int nextInt() throws IOException {in.nextToken();return (int)in.nval;} public static double nextDouble() throws IOException {in.nextToken();return in.nval;} public static float nextFloat() throws IOException {in.nextToken();return (float) in.nval;} public static String next() throws IOException {in.nextToken();return in.sval;} }