传送门:【SGU】116. Index of super-prime
题目分析:好久没写背包题了,本题只要预处理出超级素数,然后做完全背包,同时记录路径即可。
代码如下:
#include <map>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std ;
typedef long long LL ;
#define rep( i , a , b ) for ( int i = ( a ) ; i < ( b ) ; ++ i )
#define For( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define rev( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define clr( a , x ) memset ( a , x , sizeof a )
#define mid ( ( l + r ) >> 1 )
const int MAXN = 10005 ;
const int INF = 0x3f3f3f3f ;
bool prime[MAXN] ;
int super_prime[MAXN] , top ;
int dp[MAXN] ;
int pre[MAXN] ;
int a[MAXN] ;
int n ;
void get_prime () {
int cnt = 0 ;
top = 0 ;
clr ( prime , 1 ) ;
prime[1] = 0 ;
for ( int i = 2 ; i < MAXN ; ++ i ) {
if ( prime[i] ) {
++ cnt ;
if ( prime[cnt] ) super_prime[top ++] = i ;
for ( int j = i * i ; j < MAXN ; j += i ) {
prime[j] = 0 ;
}
}
}
}
void solve () {
clr ( dp , INF ) ;
dp[0] = 0 ;
rep ( i , 0 , top ) {
int cost = super_prime[i] ;
For ( j , cost , n ) if ( dp[j] > dp[j - cost] + 1 ) {
dp[j] = dp[j - cost] + 1 ;
pre[j] = j - cost ;
}
}
if ( dp[n] == INF ) printf ( "0\n" ) ;
else {
int cnt = 0 , x = n ;
printf ( "%d\n" , dp[n] ) ;
while ( x ) {
a[cnt ++] = x - pre[x] ;
x = pre[x] ;
}
sort ( a , a + cnt ) ;
rev ( i , cnt - 1 , 0 ) printf ( "%d%c" , a[i] , i ? ' ' : '\n' ) ;
}
}
int main () {
get_prime () ;
while ( ~scanf ( "%d" , &n ) ) solve () ;
return 0 ;
}