A. Prefix Sum Primes
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 nn tiles. Each of them has a single number written on it — either 11 or 22.
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 nn (1≤n≤2000001≤n≤200000) — the number of number tiles in the bag. The following line contains nn space-separated integers a1,a2,…,ana1,a2,…,an (ai∈{1,2}ai∈{1,2}) — the values written on the tiles.
Output
Output a permutation b1,b2,…,bnb1,b2,…,bn of the input sequence (a1,a2,…,an)(a1,a2,…,an) maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.
Examples
input
Copy
5 1 2 1 2 1
output
Copy
1 1 1 2 2
input
Copy
9 1 1 2 1 1 1 2 1 1
output
Copy
1 1 1 2 1 1 1 2 1
Note
The first solution produces the prefix sums 1,2,3,5,71,2,3,5,7 (four primes constructed), while the prefix sums in the second solution are 1,2,3,5,6,7,8,10,111,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.
=========================================================================
首先显然是先选2比较好,因为相对于2,1会更加灵活,如果耗费了1再选2,那么2就会变得“愚钝”,也就是会忽略很多质数,但是如果我们配合着1,2就变得灵活起来,是贪心的思想
另外本题非常考验细节,比如中途全部或者某个用完,最终没用完的情况都需要考虑到
#include<iostream>
# include<vector>
using namespace std;
int prime[200000*2+10];
bool not_prime[200000*2+10];
int tot;
void init()
{
for(int i=2;i<=200000*2;i++)
{
if(!not_prime[i])
{
tot++;
prime[tot]=i;
}
for(int j=1;j<=tot&&prime[j]*i<=200000*2;j++)
{
not_prime[i*prime[j]]=1;
if(i%prime[j]==0)
break;
}
}
}
vector<int>v;
int main()
{
//若是差别为奇数
//若干2和1,或者奇数个1
//差别是偶数,上2
//无法构成的情况,差偶数时,奇数个1,2还不够 差奇数时,1不够
init();
int n;
cin>>n;
int cnt1=0,cnt2=0;
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
if(x==1)
cnt1++;
else
cnt2++;
}
int now=1;
int pre=0;
for(int i=1;i<=tot;i++)
{
pre=prime[i-1];
if(prime[i]-pre>cnt1+cnt2*2)
{
for(int j=1;j<=cnt1;j++)
{
cout<<1<<" ";
}
for(int j=1;j<=cnt2;j++)
{
cout<<2<<" ";
}
return 0;
}
int temp=prime[i]-pre;
if(temp/2>=cnt2)
{
for(int j=1;j<=cnt2;j++)
{
cout<<2<<" ";
}
int nex=temp-cnt2*2;
for(int j=1;j<=min(cnt1,nex);j++)
{
cout<<1<<" ";
}
cnt1-=nex;
cnt2=0;
}
else
{
cnt2-=temp/2;
for(int j=1;j<=temp/2;j++)
{
cout<<2<<" ";
}
int nex=temp%2;
for(int j=1;j<=min(cnt1,nex);j++)
{
cout<<1<<" ";
}
cnt1-=nex;
}
}
for(int i=1;i<=cnt1;i++)
{
cout<<1<<" ";
}
for(int i=1;i<=cnt2;i++)
{
cout<<2<<" ";
}
return 0;
}