A. Prefix Sum Primes
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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.
小声BB
要求有尽量多的质数,
就想到先变成三,一直加2加2加2 ,
怎么变成3?先2后1,
这样子质数数量最多,
wawawawa
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX = 2e5 +5;
int n,c1,c2;
int a[MAX],ans[MAX];
int b[3];
int main(){
scanf("%d",&n);
int cur=0,top=0,tar;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
b[a[i]]++;
}
sort(a+1,a+n+1,greater<int>());
for(int i=1;i<=n;i++){
cur+=a[i];
b[a[i]]--;
ans[++top]=a[i];
if(cur == 2) {
tar=i;
break;
}
}
if(b[1]>0) {
b[1]--;
cur+=1;
ans[++top]=1;
n--;
}
for(int i = tar+1;i<=n;i++){
cur+=a[i];
b[a[i]]--;
ans[++top]=a[i];
}
for(int i=1;i<=top;i++){
printf("%d%c",ans[i],i==top?'\n':' ');
}
return 0;
}