# ZOJ 4102 Array in the Pocket （贪心）

Array in the Pocket

Time Limit: 2 Seconds      Memory Limit: 65536 KB

BaoBao has just found an array  of  integers in his left pocket. As BaoBao is bored, he decides to rearrange it into another array  of  integers such that  is a permutation of , and  for all . Please help BaoBao finish the rearragement.

If multiple valid rearrangements exist, find the smallest one among them.

Consider two arrays  and , we say  is smaller than  if there exists an integer  such that ,  for all , and .

Input

There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case:

The first line contains an integer  (), indicating the length of the array.

The second line contains  integers  (), indicating the given array.

Output

For each test case output one line containing  integers  separated by a space, indicating the answer. If there are multiple valid answers, output the smallest one. If no valid answer exists, print "Impossible" (without quotes) instead.

Please, DO NOT output extra spaces at the end of each line, or your answer may be considered incorrect!

Sample Input

3
4
4 1 3 2
4
1 1 2 3
3
1 1 1


Sample Output

1 2 4 3
2 3 1 1
Impossible

max{c[i]+sum[i]}==z时，这个位置必须填i，否则找一个字典序最小的和a[i]不相等的填上即可。

#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define rep(i,a,b) for(register int i=(a);i<=(b);i++)
#define dep(i,a,b) for(register int i=(a);i>=(b);i--)
using namespace std;
const int maxn=100010;
int n,m,k;
int a[maxn],c[maxn],sum[maxn];
int b[maxn],ok[maxn];
set<pair<int,int> >st1,st2;
set<pair<int,int> >::iterator it1,it2;
int main()
{
int T,cas=1;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
memset(c,0,sizeof(c));
memset(sum,0,sizeof(sum));
rep(i,1,n)
{
scanf("%d",&a[i]);
c[a[i]]++;
sum[a[i]]+=2;
}
st1.clear();st2.clear();
rep(i,1,n)
if(c[i]){
st1.insert(make_pair(sum[i],i));
st2.insert(make_pair(i,c[i]));
}
it1=st1.end();it1--;
if((*it1).first>n)
{
puts("Impossible");
continue;
}
rep(i,1,n)
{
st1.erase(make_pair(sum[a[i]],a[i]));
st1.insert(make_pair(--sum[a[i]],a[i]));
pair<int,int>x=*(--st1.end());
if(n-i+1==x.first)
{
b[i]=x.second;
}
else
{
if(a[i]==(st2.begin())->first)
b[i]=(++st2.begin())->first;
else b[i]=(st2.begin())->first;
}
st2.erase(make_pair(b[i],c[b[i]]));
if(--c[b[i]]>0) st2.insert(make_pair(b[i],c[b[i]]));
st1.erase(make_pair(sum[b[i]],b[i]));
if(--sum[b[i]]>0) st1.insert(make_pair(sum[b[i]],b[i]));
}
rep(i,1,n)
{
printf("%d%c",b[i],i==n?'\n':' ');
}
}
return 0;
}
/*
3
4
4 1 3 2
4
1 1 2 3
3
1 1 1
*/