标签:
卡特兰数
http://www.cnblogs.com/zhber/p/4181190.html
1 #include<cstdio> 2 #include<cstring> 3 #include<cstdlib> 4 #include<algorithm> 5 #include<iostream> 6 7 using namespace std; 8 9 void setIO(const string& s) { 10 freopen((s + ".in").c_str(), "r", stdin); 11 freopen((s + ".out").c_str(), "w", stdout); 12 } 13 template<typename Q> Q read(Q& x) { 14 static char c, f; 15 for(f = 0; c = getchar(), !isdigit(c); ) if(c == ‘-‘) f = 1; 16 for(x = 0; isdigit(c); c = getchar()) x = x * 10 + c - ‘0‘; 17 if(f) x = -x; 18 return x; 19 } 20 template<typename Q> Q read() { 21 static Q x; read(x); return x; 22 } 23 24 typedef long long LL; 25 const int LIM = 2000000, N = 1000000; 26 27 int mi[LIM+1], primes[N], tot; 28 bool flag[LIM+1]; 29 30 void get_prime(int n) { 31 for(int i = 2; i <= n; i++) { 32 if(!flag[i]) primes[tot] = i, mi[i] = tot++; 33 for(int j = 0; j < tot; j++) { 34 int k = primes[j]; 35 if((LL) i * k > n) break; 36 flag[i * k] = 1; 37 if(i % k == 0) break; 38 } 39 } 40 } 41 42 int num[N]; 43 44 void add(int x, int sign) { 45 for(int i = 0, k; k = primes[i], k * k <= x; i++) { 46 while(x % k == 0) { 47 num[i] += sign; 48 x /= k; 49 } 50 } 51 if(x ^ 1) num[mi[x]] += sign; 52 } 53 54 LL qpow(LL a, int b, int p) { 55 a %= p; 56 for(LL c = 1; ; (a *= a) %= p) { 57 if(b & 1) (c *= a) %= p; 58 if(!(b >>= 1)) return c; 59 } 60 } 61 62 int main() { 63 #ifdef DEBUG 64 freopen("in.txt", "r", stdin); 65 freopen("out.txt", "w", stdout); 66 #endif 67 68 int n, p; 69 scanf("%d%d", &n, &p); 70 get_prime(n * 2); 71 for(int i = n * 2; i > n; i--) add(i, 1); 72 for(int i = n; i > 1; i--) add(i, -1); 73 add(n + 1, -1); 74 75 int res = 1; 76 for(int i = 0; i < tot; i++) if(num[i]) { 77 res = (LL) res * qpow(primes[i], num[i], p) % p; 78 } 79 printf("%d\n", res); 80 81 return 0; 82 }
标签:
原文地址:http://www.cnblogs.com/showson/p/5103669.html