time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output
We’re giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.
Can you win the prize? Hurry up, the bags are waiting!
Input
The first line of the input contains a single integer n (1≤n≤200000) — the number of number tiles in the bag. The following line contains n space-separated integers a1,a2,…,an (ai∈{1,2}) — the values written on the tiles.
Output
Output a permutation b1,b2,…,bn of the input sequence (a1,a2,…,an) maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.
Examples
inputCopy
5
1 2 1 2 1
outputCopy
1 1 1 2 2
inputCopy
9
1 1 2 1 1 1 2 1 1
outputCopy
1 1 1 2 1 1 1 2 1
Note
The first solution produces the prefix sums 1,2,3,5,7 (four primes constructed), while the prefix sums in the second solution are 1,2,3,5,6,7,8,10,11 (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible.
这是我在cf上写的第一个题,打卡~~
大概意思就是说把n个数排个序,使前缀和中的素数尽量多
因为无论怎么排序,他所有数总和(sum)是有限的,也即最大的素数<=sum
又因为所有的素数除了2都是奇数,所以两个相邻的前缀和之间尽量不要跳过奇数
上代码:
#include<stdio.h>
int main()
{
int n,two=0,one=0,temp;
scanf("%d",&n);
//统计1和2的数量
for(int i = 1; i <= n; i++)
{
scanf("%d",&temp);
if(temp==1)
one++;
else
two++;
}
//没有1的特殊情况
//题目好像没有要求末尾无空格,但我习惯了也就这么写了,下一种情况同此
if(one==0)
{
printf("2");
for(int i = 1; i <two;i++)
printf(" 2");
}
//没有2的特殊情况
else if(two==0)
{
printf("1");
for(int i = 1; i <one;i++)
printf(" 1");
}
//一般的情况,要将2和3体现在前缀和中。
else
{
printf("2 1");
for(int i = 1; i < two; i++)
printf(" 2");
for(int i = 1; i < one;i++)
printf(" 1");
}
return 0;
}