1. 程式人生 > >SPOJ CZ_PROB1 - Summing to a Square Prime

SPOJ CZ_PROB1 - Summing to a Square Prime

tags poj ons 算法 ++ pair ont logs 16px

題目鏈接:http://www.spoj.com/problems/CZ_PROB1/

題目大意:Sp2 是所有素數中能夠被分解為兩個數的平方和的素數的集合。P(a,b)指的是在a的劃分中,最大元素不超過b的劃分的個數(就是那個經典整數劃分動態規劃題)。給你個n,k,問P(sp2[n],k)是多少。

  • 0<T<501
  • 0<n<501
  • 1<SP2(n)<7994
  • 0<k<4

解題思路:既然題中已經給出sp2集合的限制,那麽sp2直接打表,按照經典動態規劃算法計算p(a,b)然後再打表,然後。。。就沒有然後了

轉移方程:

if(j > i)  p[i][j] = p[i][i];


else if(j == i)  p[i][j] = p[i][j - 1] + 1;
else  p[i][j] = p[i][j - 1] + p[i - j][j];

初始化的時候 p[1][1] = p[1][2] = p[1][3] = p[1][4] = 1,其余0即可。

代碼:

 1 const int maxn = 1e4 + 5;
 2 bool vis[maxn];
 3 vector<int> vec;
 4 int n, k;
 5 int p[maxn][10];
 6 
 7 bool isprime(int x){
 8     if(x == 2
|| x == 3) return true; 9 if(x == 1 || x % 2 == 0) return false; 10 for(int i = 2; i * i <= x; i++) 11 if(x % i == 0) return false; 12 return true; 13 } 14 void dowork(){ 15 memset(vis, 0, sizeof(vis)); 16 for(int i = 1; i <= 90; i++){ 17 for(int j = 1; j <= 90
; j++){ 18 int x = i * i + j * j; 19 if(isprime(x) && x < maxn && vis[x] == 0) { 20 vec.push_back(x); 21 vis[x] = true; 22 } 23 } 24 } 25 sort(vec.begin(), vec.end()); 26 memset(p, 0, sizeof(p)); 27 p[1][1] = p[1][2] = p[1][3] = p[1][4] = 1; 28 for(int i = 2; i < 8000; i++){ 29 p[i][1] = 1; 30 for(int j = 1; j < 4; j++){ 31 if(j > i) p[i][j] = p[i][i]; 32 else if(j == i) p[i][j] = p[i][j - 1] + 1; 33 else p[i][j] = p[i][j - 1] + p[i - j][j]; 34 } 35 } 36 } 37 void solve(){ 38 int a = vec[n - 1], b = k; 39 printf("%d\n", p[a][b]); 40 } 41 42 int main(){ 43 dowork(); 44 int t; 45 scanf("%d", &t); 46 while(t--){ 47 scanf("%d %d", &n, &k); 48 solve(); 49 } 50 }

題目:

CZ_PROB1 - Summing to a Square Prime

#math #dynamic-programming

SP2={pp:prime(?x1,x2Z,p=x21+x22)}SP2={p∣p:prime∧(?x1,x2∈Z,p=x12+x22)} is the set of all primes that can be represented as the sum of two squares. The function SP2(n)SP2(n) gives the nnth prime number from the set SP2SP2. Now, given two integers nn(0<n<5010<n<501) and kk (0<k<40<k<4), find p(SP2(n),k)p(SP2(n),k) where p(a,b)p(a,b) gives the number of unordered ways to sum to the given total ‘aa’ with ‘bb’ as its largest possible part. For example: p(5,2)=3p(5,2)=3 (i.e. 2+2+12+2+1, 2+1+1+12+1+1+1, and 1+1+1+1+11+1+1+1+1). Here 55 is the total with 22 as its largest possible part.

Input

The first line gives the number of test cases TT followed by TT lines of integer pairs, nn and kk.

Constraints

  • 0<T<5010<T<501
  • 0<n<5010<n<501
  • 1<SP2(n)<79941<SP2(n)<7994
  • 0<k<40<k<4

Output

The p(SP2(n),k)p(SP2(n),k) for each nn and kk. Append a newline character to every test cases’ answer.

Example

Input:
3
2 2
3 2
5 3

Output:
3
7
85

SPOJ CZ_PROB1 - Summing to a Square Prime