hdu4651 Partition

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=4651



Partition


Problem Description
How many ways can the numbers 1 to 15 be added together to make 15? The technical term for what you are asking is the "number of partition" which is often called P(n). A partition of n is a collection of positive integers (not necessarily distinct) whose sum equals n.

Now, I will give you a number n, and please tell me P(n) mod 1000000007.
 

Input
The first line contains a number T(1 ≤ T ≤ 100), which is the number of the case number. The next T lines, each line contains a number n(1 ≤ n ≤ 105) you need to consider.

 

Output
For each n, output P(n) in a single line.
 

Sample Input
4 5 11 15 19
 

Sample Output
7 56 176 490
 

題意:

1,2,……n中元素任意求和和爲n的個數即爲P(n),元素可以重複,要求求出P(n);


舉例:n=5;  

  • 5
  • 4 + 1
  • 3 + 2
  • 3 + 1 + 1
  • 2 + 2 + 1
  • 2 + 1 + 1 + 1
  • 1 + 1 + 1 + 1 + 1

所以P(5)=7;


參考網址: https://en.wikipedia.org/wiki/Partition_(number_theory)  五邊形數定理


P(n)=P(n-1)+P(n-2)-P(n-5)-P(n-7)+P(n-12)+……

不難得到

P(n)=∑(-1)^k * P(n-q[j])

其中q[j]爲五邊形數

k=1    q[1]=1,q[2]=2;

k=2    q[3]=5,q[4]=7;

k=3    q[5]=12,q[6]=14;

…………

k=n   q[2*k-1]=k*(3*k-1)/2 , q[2*k]=k*(3*k+1)/2;

然後套公式即可


#include <cstdio>
#include <iostream>
#include <cstring>
#include<cmath>
#include <string>
#include <queue>
#include <vector>
#include <set>
#include <stdlib.h>
#include <time.h>
//#include <map>
#include <algorithm>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const double pi=acos(-1);
#define N 1005
//map<string,int>q;
//priority_queue<int>pq;
//priority_queue<int ,vector<int>,greater<int>>pq;
#define mod 1000000007
LL p[100010];
int q[100010];
int main()
{
    int k=1,t,n;
    q[0]=0;
    for(int i=1; q[k-1]<=100000; i++)
    {
        q[k++]=i*(3*i-1)/2;
        q[k++]=i*(3*i+1)/2;
    }
    //for(int i=0;i<10;i++)
      //  cout<<q[i]<<endl;

    p[0]=1;
    p[1]=1;
    p[2]=2;
    for(int i=3; i<=100000; i++)
    {
        p[i]=0;
        for(int j=1; i-q[j]>=0; j++)
        {
            k=0;
            if(j%2==0) k=j/2;
            else k=(j+1)/2;
            if(k%2==0) p[i]=(p[i]-p[i-q[j]])%mod;
            else p[i]=(p[i]+p[i-q[j]])%mod;
        }
    }
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        printf("%lld\n",(p[n]+mod)%mod);
    }
    return 0;
}


發佈了48 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章