fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main(){
  5. ios::sync_with_stdio(false);
  6. cin.tie(nullptr);
  7.  
  8. int t;
  9. cin>>t;
  10.  
  11. while(t--){
  12. int n;
  13. cin>>n;
  14.  
  15. vector<long long> b,c,a,d;
  16.  
  17. for(int i=0;i<n;i++){
  18. long long x;
  19. cin>>x;
  20.  
  21. bool two=(x%2==0);
  22. bool three=(x%3==0);
  23.  
  24. if(two&&three) a.push_back(x);
  25. else if(two) b.push_back(x);
  26. else if(three) c.push_back(x);
  27. else d.push_back(x);
  28. }
  29.  
  30. vector<long long> ans;
  31.  
  32. if((int)b.size()>=(int)c.size()){
  33. for(auto x:d) ans.push_back(x);
  34. for(auto x:b) ans.push_back(x);
  35. for(auto x:a) ans.push_back(x);
  36. for(auto x:c) ans.push_back(x);
  37. }
  38. else{
  39. for(auto x:d) ans.push_back(x);
  40. for(auto x:c) ans.push_back(x);
  41. for(auto x:a) ans.push_back(x);
  42. for(auto x:b) ans.push_back(x);
  43. }
  44.  
  45. for(int i=0;i<n;i++){
  46. if(i) cout<<" ";
  47. cout<<ans[i];
  48. }
  49. cout<<endl;
  50. }
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0.01s 5288KB
stdin
5
6
12 7 9 4 18 5
4
3 6 2 8
7
1 10 15 20 3 6 9
5
11 14 21 2 5
3
6 6 6
stdout
7 5 4 12 18 9
2 8 6 3
1 15 3 9 6 10 20
11 5 14 2 21
6 6 6