fork download
  1. #include <bits/stdc++.h>
  2. #define M 1000000007
  3. #define pb push_back
  4. typedef long long ll;
  5. using namespace std;
  6. int atoi(string s)
  7. {
  8. int num = 0;
  9. for(int i=0;i<s.length();i++)
  10. num = num*10 + (s[i]-'0');
  11. return num;
  12. }
  13. vector<ll> vc,ls[3];
  14. int comp(ll a,ll b)
  15. {
  16. return (a>b);
  17. }
  18. int main()
  19. {
  20. //if (in.is_open())
  21. {
  22. int tc;
  23. cin >> tc;
  24. //tc = atoi(str);
  25. while(tc--)
  26. {
  27. ls[0].clear(); ls[1].clear(); ls[2].clear(); vc.clear();
  28. ll n,len;
  29. cin >> n;
  30. ll ar[n],sum=0,flag=0;
  31. for(int i=0;i<n;i++)
  32. {
  33. cin >> ar[i];
  34. ls[ar[i]%3].pb(ar[i]);
  35. sum = (sum+ar[i])%3;
  36. if(ar[i]==0) flag=1;
  37. //cout<<ls[ar[i]%3].back()<<" ";
  38. }
  39. if(!flag)
  40. {
  41. cout << "-1\n";
  42. continue;
  43. }
  44. sort(ls[0].begin(),ls[0].end(),comp);
  45. sort(ls[1].begin(),ls[1].end(),comp);
  46. sort(ls[2].begin(),ls[2].end(),comp);
  47.  
  48. if(sum==1)
  49. {
  50. if(!ls[1].empty())
  51. ls[1].pop_back();
  52. else
  53. {
  54. len = ls[2].size();
  55. for(int i=0;i<(len%3);i++)
  56. ls[2].pop_back();
  57. }
  58. }
  59. if(sum==2)
  60. {
  61. if(!ls[2].empty())
  62. ls[2].pop_back();
  63. else
  64. {
  65. len = ls[1].size();
  66. for(int i=0;i<(len%3);i++)
  67. ls[1].pop_back();
  68. }
  69. }
  70. vc.insert(vc.end(),ls[0].begin(),ls[0].end());
  71. vc.insert(vc.end(),ls[1].begin(),ls[1].end());
  72. vc.insert(vc.end(),ls[2].begin(),ls[2].end());
  73. sort(vc.begin(),vc.end(),comp);
  74. if(ls[1].empty() && ls[2].empty() && (ls[0].front()==0))
  75. {
  76. cout << "0\n";
  77. continue;
  78. }
  79. for(int i=0;i<vc.size();i++)
  80. cout << vc[i];
  81. cout << "\n";
  82. }
  83. }
  84. //in.close();
  85. //out.close();
  86. return 0;
  87. }
  88.  
Runtime error #stdin #stdout 0s 2748KB
stdin
Standard input is empty
stdout
Standard output is empty