标签:
题目链接:http://acm.swust.edu.cn/problem/0247/
2 3 97
20 40 37
0 0 0
|
10
32
|
Lucas定理用来求C(a,b)mod p的值,其中p为素数。
数学表达式为:
Lucas(a,b,q)=C(a%q,b%q)*Lucas(a/p,b/p,p);
Lucas(a,0,q)=0;
模运算与基本四则运算有些相似,但是除法例外。其规则如下:
(a + b) % p = (a % p + b % p) % p (1)
(a - b) % p = (a % p - b % p) % p (2)
(a * b) % p = (a % p * b % p) % p (3)
a ^ b % p = ((a % p)^b) % p (4)
代码如下:
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 #define maxn 405 5 using namespace std; 6 long long dp[maxn][maxn], n, m, p; 7 long long Lucas(long long n, long long m, long long p){ 8 //Lucas定理 9 if (n <= p && m <= p) 10 return dp[n][m]; 11 else 12 return (Lucas(n / p, m / p, p)*dp[n%p][m%p]) % p; 13 } 14 15 //杨辉三角求组合数 16 void init(){ 17 int i, left, right; 18 for (i = 1; i <= p; i++){ 19 dp[i][0] = dp[i][i] = 1; 20 left = 1, right = i - 1; 21 while (left <= right){ 22 dp[i][left] = (dp[i - 1][left - 1] + dp[i - 1][left]) % p; 23 dp[i][right--] = dp[i][left++];//组合数性质dp[i][j]=dp[i][i-j]; 24 } 25 } 26 } 27 int main(){ 28 while (cin >> n >> m >> p && n && m && p){ 29 memset(dp, 0, sizeof(dp)); 30 init(); 31 cout << Lucas(n + m, min(n, m), p) << endl; 32 } 33 return 0; 34 }
乱搞的Java代码如下:
1 import java.math.*; 2 import java.io.*; 3 import java.util.*; 4 public class Main{ 5 static int DP[][] = new int[401][401]; 6 static int p; 7 public static void main(String[] args) 8 { 9 Scanner cin = new Scanner(System.in); 10 int a, b; 11 while (cin.hasNext()){ 12 a = cin.nextInt(); 13 b = cin.nextInt(); 14 p = cin.nextInt(); 15 if (a == 0) 16 break; 17 initDp(); 18 System.out.println(sloveRe(a + b, b > a ? a : b)); 19 } 20 } 21 private static void initDp(){ 22 int i, j; 23 for (i = 0; i <= p; i++){ 24 DP[i][0] = 1; 25 } 26 for (i = 1; i <= p; i++){ 27 for (j = 1; j <= p; j++){ 28 DP[i][j] = (DP[i - 1][j] + DP[i - 1][j - 1]) % p; 29 } 30 } 31 } 32 private static int sloveRe(int n, int m){ 33 if (n <= p&&m <= p) 34 return DP[n][m]; 35 else 36 return (sloveRe(n / p, m / p)*DP[n%p][m%p]) % p; 37 } 38 }
[Swust OJ 247]--皇帝的新衣(组合数+Lucas定理)
标签:
原文地址:http://www.cnblogs.com/zyxStar/p/4587185.html