思路
我们先分类讨论一下:
- 当 时显然直接输出原数组即可。
- 当 时显然怎么排列都是无解的,直接输出 -1.
- 当 时,我们发现如果有 0 和 1 相交肯定是不优的,这很好理解,所有数都是 1 的倍数。那么显然我们需要让所有的 0 只和 2 相交。但这时会出现一个新的问题,2 和 1 相交了,怎么判断是否有解呢?其实也很好想,因为 2 和 3(1+2)可以表示出所有 > 1 的数,所以我们只需判断 s-1 是否 = 即可。
code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6+7;
int n, s;
int a[N];
int cnt[3];
void Sol()
{
cnt[0] = cnt[1] = cnt[2] = 0;
cin >> n >> s;
for(int i(1); i <= n; ++i)
cin >> a[i], cnt[a[i]]++;
if(s < cnt[1] + cnt[2] * 2)
{
for(int i(1); i <= n; ++i)
cout << a[i] << " \n"[i == n];
return ;
}
if(s == cnt[1] + cnt[2] * 2)return cout << "-1\n", void();
if(s - cnt[1] - cnt[2] * 2 > 1)return cout << "-1\n", void();
for(int i(1); i <= cnt[0]; ++i)
cout << "0 ";
for(int i(1); i <= cnt[2]; ++i)
cout << "2 ";
for(int i(1); i <= cnt[1]; ++i)
cout << 1 << " \n"[i == cnt[1]];
}
int main()
{
cin.tie(0) -> ios::sync_with_stdio(false);
int T;
cin >> T;
while(T--)Sol();
return 0;
}