题目链接:http://hihocoder.com/problemset/problem/1356
时间限制:
10000ms
单点时限:
1000ms
内存限制:
256MB
-
4 2 1 3 3
样例输出
-
1 3 2 3
描述
给定一个包含N个整数的数组A。你的任务是将A重新排列,使得任意两个相等的整数在数组中都不相邻。
如果存在多个重排后的数组满足条件,输出字典序最小的数组。
这里字典序最小指:首先尽量使第一个整数最小,其次使第二个整数最小,以此类推。
输入
第一行包含一个整数N,表示数组的长度。(1 <= N <= 100000)
第二行包含N个整数,依次是 A1, A2, ... AN。(1 <= Ai <= 1000000000)
输出
输出字典序最小的重排数组。如果这样的数组不存在,输出-1。
思路:显然的一个贪心思路是,每次选可以选的最小的数。这样每次选过一个数,纪录为last,选下一个数时要保证不是last即可,在这种贪心思路下若有解必然是最优解,现在就需要判断什么时候无解,当某个数的个数cnt满足2 * cnt - 1 > n时无解,可知若序列中个数最大的cnt满足有解的话,可以这样贪心构造始终保持有解,也就是当最大cnt的数满足2 * cnt - 1 = n时就必须选这个数即可。
可以按pair<cnt, num>存在map里,贪心构造即可。
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5;
int n;
int a[N];
map<int, int> cnt;
set< pair<int, int> > S;
vector<int> vec;
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
cnt[a[i]]++;
}
for (map<int, int>::iterator it = cnt.begin(); it != cnt.end(); it++)
S.insert(make_pair(it->second, it->first));
if ((--S.end())->first * 2 - 1 > n)
{
puts("-1");
return 0;
}
int pre_x = -1;
for (int i = 1; i <= n; i++)
{
int x;
if ((--S.end())->first * 2 - 1 == (n + 1 - i))
x = (--S.end())->second;
else
{
map<int, int>::iterator it = cnt.begin();
if (it->first == pre_x) it++;
x = it->first;
}
S.erase(make_pair(cnt[x], x));
if (--cnt[x] > 0)
S.insert(make_pair(cnt[x], x));
else
cnt.erase(x);
printf("%d%c", x, " \n"[i == n]);
pre_x = x;
}
}