D. Simple Subset 题目链接,点这里。
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
A tuple of positive integers {x1, x2, …, xk} is called simple if for all pairs of positive integers (i, j) (1 ≤ i < j ≤ k), xi + xj is a prime.
You are given an array a with n positive integers a1, a2, …, an (not necessary distinct). You want to find a simple subset of the array a with the maximum size.
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Let’s define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it.
Input
The first line contains integer n (1 ≤ n ≤ 1000) — the number of integers in the array a.
The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a.
Output
On the first line print integer m — the maximum possible size of simple subset of a.
On the second line print m integers bl — the elements of the simple subset of the array a with the maximum size.
If there is more than one solution you can print any of them. You can print the elements of the subset in any order.
Examples
input
2
2 3
output
2
3 2
input
2
2 2
output
1
2
input
3
2 1 1
output
3
1 1 2
input
2
83 14
output
2
14 83
题意:n , 然后是n个数字,求这n个数字中的一个最长序列,要求是序列中任意两个数相加都是素数。
可以推出一个小小的规律:除了存在多个1可以和一个数组成的集合中任意两个数相加能够是素数外,不存在任意三个数能两两相加成为素数,
思路:判断1的个数。
如果大于等于2的话,先输出,再找一个和1相加是素数的数,然后直接break掉;
如果小于2,任意找两个和为素数的数输出;
如果没有两个数相加是素数,就输出任意一个数。
代码:
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#define maxn 2000050
//题目给的是一百万数据范围,但是相加的话可能会有2000 000,小的话RE;
using namespace std;
int su[maxn];
//素数打表;
void init()
{
memset(su,0,sizeof(su)); //素数为0;
su[1]=1;
for(int i=2; i<=maxn; i++)
if(su[i]==0)
for(int j=2*i; j<=maxn; j+=i)
su[j]=1; //非素数为1;
}
int main()
{
init();//调用打表函数;
int f[1005],n;
while(~scanf("%d",&n))
{
int cc=0; //标记1的个数;
for(int i=1; i<=n; i++)
{
scanf("%d",&f[i]);
if(f[i]==1)
cc++;
}
if(cc<2)// 如果1的个数小于2,证明只需要找到两个和为素数的数输出就可以;
{
int ans=0;
for(int i=1; i<=n; i++)
{
for(int j=i+1; j<=n; j++)
{
if(su[f[i]+f[j]]==0)//两个数的和为素数;
{
ans=1;//标记,跳出循环;
printf("2\n%d %d\n",f[i],f[j]);
break;
}
}
if(ans==1)//跳出循环;
break;
}
if(ans==0)//没有两个数相加是素数,随意输出一个数;
printf("1\n%d\n",f[1]);
}
else
{
int a=-1;
for(int i=1; i<=n; i++)
if(su[f[i]+1]==0&&f[i]!=1)
{
cc++;
a=f[i];
break;
}
printf("%d\n",cc);//输出个数;
if(a!=-1)//如果a不是 -1 ,也就是存在一个数 +1 是素数;
{
printf("%d ",a);//输出;
cc--; //个数总和要 -1;
}
//注意一下格式就可以了。
for(int i=1; i<cc; i++)
printf("1 ");
printf("1\n");
}
}
return 0;
}
本文介绍了一种算法,用于解决寻找整数数组中最长子集的问题,要求该子集中任意两个元素之和均为素数。文章给出了具体的实现思路及代码示例。
207

被折叠的 条评论
为什么被折叠?



