outputstandard output
This is the hard version of the problem. The difference between the versions is that in the easy version all prices ai are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage’s birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row and they are numbered from 1 to n from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.
An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.
You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.
Input
The first line contains a single integer n (1≤n≤105) — the number of ice spheres in the shop.
The second line contains n integers a1,a2,…,an (1≤ai≤109) — the prices of ice spheres.
Output
In the first line print the maximum number of ice spheres that Sage can buy.
In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.
Example
inputCopy
7
1 3 2 2 4 5 4
outputCopy
3
3 1 4 2 4 2 5
Note
In the sample it’s not possible to place the ice spheres in any order so that Sage would buy 4 of them. If the spheres are placed in the order (3,1,4,2,4,2,5), then Sage will buy one sphere for 1 and two spheres for 2 each.
题意:
构造一个序列,使得存在 bi < b[i-1] && bi < b[i+1]的对数最多,序列两端不算。
思路:
贪心构造的思路不难得出,如何写的简便写,再开一个数组,从2开始每次隔一个位置插入小的,间距为2
同理 从1开始每次隔一个位置插入大的,间距也为2
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 50;
int a[N],b[N];
int main(){
int n;
cin >> n;
for(int i = 1;i <= n;i ++){
cin >> a[i];
}
sort(a + 1,a + 1 + n);
//1 2 2 3 4 4 5
int l = 1;//从小到大
for(int i = 2;i <= n;i += 2){
b[i] = a[l ++];
}
for(int i = 1;i <= n;i += 2){
b[i] = a[l ++];
}
int res= 0 ;
for(int i = 2;i <= n - 1;i += 2){
res += (b[i] < b[i - 1] && b[i] < b[i + 1]);
}
cout << res << '\n';
for(int i = 1;i <= n;i ++){
cout << b[i] << ' ';
}
}