Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /** An array of integers is provided.
- You need to arrange the numbers such that no 2 consecutive numbers sum is divisible by 3.
- If no such arrangement is possible then return(“impossible”), else return the arrangement.
- **/
- #include<bits/stdc++.h>
- #define pb push_back
- using namespace std;
- int T, N, x, z, o, t;
- vector<int> zeros;
- vector<int> ones;
- vector<int> twos;
- list<int> ans;
- // Input:
- // 7
- // 11
- // 1 1 0 0 0 0 0 0 2 2 2
- // 9
- // 1 1 0 0 0 0 0 0 2
- // 6
- // 0 1 0 1 2 2
- // 4
- // 0 0 0 1
- // 4
- // 1 2 1 2
- // 4
- // 2 2 2 1
- // 5
- // 0 0 0 2 2
- // Output:
- // 0 1 0 1 0 2 0 2 0 2 0
- // Impossible
- // 0 1 1 0 2 2
- // Impossible
- // Impossible
- // Impossible
- // 0 2 0 2 0
- int solve(){
- z = zeros.size();
- o = ones.size();
- t = twos.size();
- if(!z && o && t) // if no 0, but both 1 and 2
- return 0;
- if(z && !o && !t) // if only 0
- return 0;
- if(o+t+1 < z) // if more 0s than total+1 :: there can be maximum total+1 places for 0s for valid arrangement
- return 0;
- return 1;
- }
- void arrange(){
- if(o && t) // if both 1s and 2s are there, keep aside a 0 to be kept in between the 1's series and 2's series
- z--;
- for(int i=0; i<o; ++i){ // fill up 0s and 1s
- if(z)
- ans.pb(zeros[--z]);
- ans.pb(ones[i]);
- }
- if(o && t) // if both 1s and 2s are there, the kept aside 0 needs to be put now
- z++;
- for(int i=0; i<t; ++i){ // fill up 0s and 2s
- if(z)
- ans.pb(zeros[--z]);
- ans.pb(twos[i]);
- }
- if(z) // if there's a last zero left
- ans.pb(zeros[--z]);
- for(auto it=ans.begin(); it!=ans.end(); ++it)
- cout<<*it<<" ";
- cout<<endl;
- }
- int main(){
- cin>>T;
- while(T--){
- cin>>N;
- zeros.clear();
- ones.clear();
- twos.clear();
- ans.clear();
- for(int i=0; i<N; ++i){
- cin>>x;
- if(!(x%3))
- zeros.pb(x);
- else if(x%3 == 1)
- ones.pb(x);
- else
- twos.pb(x);
- }
- int res = solve();
- if(!res)
- cout<<"Impossible"<<endl;
- else
- arrange();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement