【Codeforces 1419 D2】Sage‘s Birthday (hard version),二分答案

problem

D2. Sage’s Birthday (hard version)
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
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.

solution

/*
题意:
+ 给出n(1e5)个物品的价格,当且仅当a[i]低于相邻两个物品时会被购买
+ 重新排列顺序,使得被购买的物品尽可能多,输出顺序。
思路:
+ 先升序排序。假设能买x个,那我们需要x+1个更大的球。
+ 判断条件是分明确,复杂度可以二分。
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 2e5+10;
int n, a[maxn];
bool check(int x){
	if(2*x+1>n)return false;
	int pa = 0, pb = n-(x+1);
	vector<int>v;
	for(int i = 0; i < 2*x+1; i++){
		if(i%2==0)v.push_back(a[pb++]);
		else v.push_back(a[pa++]);
	}
	for(int i = 1; i < 2*x+1; i+=2)
		if(v[i]>=v[i-1]||v[i]>=v[i+1])return false;
	return true;
}
int main(){
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i = 0; i < n; i++)cin>>a[i];
	sort(a,a+n);
	int l = 0, r = n+1;
	while(l<r){
		int m = l+r>>1;
		if(check(m))l = m+1;
		else r = m;
	}
	l--;
	cout<<l<<"\n";
	vector<int>v;
	int pa = 0, pb = n-(l+1);
	for(int i = 0; i < 2*l+1; i++){
		if(i%2==0)v.push_back(a[pb++]);
		else v.push_back(a[pa++]);
	}
	for(int i = pa; i < n-(l+1); i++)
		v.push_back(a[i]);
	for(int i = 0; i < v.size(); i++)
		cout<<v[i]<<" ";
	return 0;
}


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页