您的位置:首页 > 其它

sgu 116 Index of super-prime

2012-10-26 11:38 381 查看
题目描述:


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
==inf)printf("0\n");
else{
printf("%d\n",dp
);
int i=0;
while(fa
!=-1){
a[i++]=fa
;
n=n-fa
;
}
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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: