CodeForces-1149-A Prefix Sum Primes

Topic link:Prefix Sum Primes
Description:
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
input
5
1 2 1 2 1
output
1 1 1 2 2
input
9
1 1 2 1 1 1 2 1 1
output
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.

Intentional analysis:
To solve this problem,you’d better know a rule——The difference between all adjacent prime numbers except 2, 3 is even.So what we should is just get the number of occurrences of 1 and 2,judge and print.There are three situations:

• 1.The number of occurrences of 1 is 0.
• 2.The number of occurrences of 2 is 0.
• 3.Both 1 and 2 have appeared.

Where does it reflect greed?
If the first two numbers are done,and you still have 2 ,just print it,and then print 1.

Click to see Chinese Intentional analysis 为了解决这个问题，有个规则你是必须要知道的——除了2，3之外的所有相邻的素数的差都是偶数。所以我们只需要知道给的数据中1，2出现几次就行了。这里总共有三种情况： 一： 1没有出现过。 二： 2没有出现过。 三： 1，2都出现过。 能体现出贪心的是哪里呢？ 就是当你处理完前两个质数2，3之后，如果你还有2，就把2先输出完，然后再输出剩下的1即可。

Code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
int x,a=0,b=0,n;
cin>>n;
while(n--)
{
cin>>x;
if(x==1) a++;
else b++;
}
if(a==0)
{
while(b--)
cout<<"2 ";
cout<<endl;
return 0;
}
if(b==0)
{
while(a--)
cout<<"1 ";
cout<<endl;
return 0;
}
else
{
cout<<"2 1 ";
a-=1;
b-=1;
while(b--)
cout<<"2 ";
while(a--)
cout<<"1 ";
cout<<endl;
return 0;
}
}


There are many useful rules that I don’t know,still have to do more questions.