sgu 116 Index of super-prime

本文探讨了如何通过动态规划解决寻找特定数值为超级质数索引的问题,包括输入处理、状态定义、状态转移方程及代码实现,旨在简化算法以避免超时错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

116. Index of super-prime

time limit per test: 0.5 sec.
memory limit per test: 4096 KB

Let P1, P2, … ,PN, … be a sequence of prime numbers. Super-prime number is such a prime number that its current number in prime numbers sequence is a prime number too. For example, 3 is a super-prime number, but 7 is not. Index of super-prime for number is 0 iff it is impossible to present it as a sum of few (maybe one) super-prime numbers, and if such presentation exists, index is equal to minimal number of items in such presentation. Your task is to find index of super-prime for given numbers and find optimal presentation as a sum of super-primes.

Input

There is a positive integer number in input. Number is not more than 10000.

Output

Write index I for given number as the first number in line. Write I super-primes numbers that are items in optimal presentation for given number. Write these I numbers in order of non-increasing.

Sample Input

6

Sample Output

2
3 3

事实证明:搜索是会TLE的,至少我的搜索是会T的,没办法,改思路,然后就是dp
结果就d出来了
状态:dp[i] 表示i需要的个数;
状态转移: dp[i]=min(dp[j]+1) i-j is a super-prime
那么 就是 100*10000的复杂度,还是可以接受的。

附上代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>

#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))

using namespace std;
int const nMax = 10001;
typedef int LL;
typedef pair<LL,LL> pij;

int a[nMax],b[nMax],_b=1,p[nMax],k;
int ans[nMax];
void init(){
    int i;
    for(i=2;i<100;i++)if(!a[i]){
        b[_b++]=i;
        for(int j=i*i;j<nMax;j+=i)a[j]=1;
    }
    for(;i<nMax;i++)if(!a[i])b[_b++]=i;
    for(k=1;b[k]<_b;k++){
        p[k]=b[b[k]];
    }
    return ;
}
int fa[nMax],dp[nMax];

bool DP(int n)
{
    for(int i=0;i<=n;i++)dp[i]=inf;
    dp[0]=0;
    memset(fa,-1,sizeof(fa));
    for(int i=1;i<=n;i++){
        for(int j=1;j<=k;j++)if(i>=p[j]){
            if(dp[i-p[j]]!=inf){
                if(dp[i]>dp[i-p[j]]+1){
                    dp[i]=dp[i-p[j]]+1;
                    fa[i]=p[j];
                }
            }
        }else break;
    }
    if(dp[n]==inf)printf("0\n");
    else{
        printf("%d\n",dp[n]);
        int i=0;
        while(fa[n]!=-1){
            a[i++]=fa[n];
            n=n-fa[n];
        }
        sort(a,a+i,greater<int>() );
        for(int j=0;j<i;j++)if(j==0)printf("%d",a[j]);
        else printf(" %d",a[j]);
        printf("\n");
    }
    return true;
}
int main()
{
    int n;
    init();
    cin>>n;
    int l;
    for(l=k-1;l>=1;l--)if(n>=p[l])break;
    DP(n);
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值