【CodeForces - 1150C】Prefix Sum Primes(思维)
題干:
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?11or?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
5 1 2 1 2 1Output
1 1 1 2 2Input
9 1 1 2 1 1 1 2 1 1Output
1 1 1 2 1 1 1 2 1Note
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.
題目大意:
?給你N個數(shù),每個數(shù)都是1或者2.現(xiàn)在讓你求一個排列,使得這個排列的前綴和數(shù)組 擁有最多的素數(shù)。
解題報告:
直接貪心就行了,不難發(fā)現(xiàn)到3以后,就先填2,,不夠再填1,這樣一定是最優(yōu)的。(因為你湊出了一個奇數(shù),并且素數(shù)一定是奇數(shù),而整個序列的最后一個數(shù)又是一定的,也就是前綴和數(shù)組的最后一個數(shù)一定是sum(ai),是個定值,所以這樣構(gòu)造一定是最優(yōu)解。)
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define F first #define S second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int n,a[MAX],bk[3]; int ans[MAX]; int main() {cin>>n;for(int i = 1; i<=n; i++) cin>>a[i],bk[a[i]]++;sort(a+1,a+n+1,greater<int>());int cur = 0,top = 0,tar;for(int i = 1; i<=n; i++) {cur += a[i];bk[a[i]]--;ans[++top]=a[i];if(cur == 2) {tar = i;break; }}if(bk[1]>0) bk[1]--,cur+=1,ans[++top]=1,n--;for(int i = tar+1; i<=n; i++) {cur+=a[i];bk[a[i]]--;ans[++top]=a[i];}for(int i = 1; i<=top; i++) printf("%d%c",ans[i],i == top ? '\n' :' ');return 0 ; }注意姿勢啊:第一個for的bk[a[i]]--別放在if中。第二個for別直接i<=n-1,,因為有可能進不去上面那個if。。會造成輸出的個數(shù)不是n個數(shù)。
總結(jié)
以上是生活随笔為你收集整理的【CodeForces - 1150C】Prefix Sum Primes(思维)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 坦克300绝配!长城上线纯电越野自行车:
- 下一篇: 天玑9000+顶级芯!iQOO 10系列