Problem link : ADJHATE Problem - CodeChef
My Solution : https://www.codechef.com/viewsolution/60500690
PS : It’s passing all sample test cases but failing for some hidden cases , i am unable to find them please help.
consider below test case:
1
5
2 4 6 8 3
Your output is -1 but 3 2 4 6 8 can be the solution as the absolute differences will be 1 2 2 2 and the sum will be 7 which is odd.
Another problem with your solution is,
consider this test case
1
5
1 2 3 4 5
your output:
2 1 4 3 576556042672268600
res[4] gives the garbage value
Thanks for your help , but still it is giving wa
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <unordered_map>
#include <cmath>
using namespace std;
typedef long long int ll;
void solve(){
ll n;
cin>>n;
vector<ll> v;
vector<ll> even;
vector<ll> odd;
for(ll i=0;i<n;i++){
ll d;
cin>>d;
v.push_back(d);
if(d & 1 !=0){
odd.push_back(d);
}
else{
even.push_back(d);
}
}
sort(even.begin(),even.end());
sort(odd.begin(),odd.end());
ll es=even.size();
ll os=odd.size();
if(os==0 || es==0){
cout<<-1<<endl;
}
else if(odd.size() & 1 !=0){
for(ll i=0;i<v.size();i++){
cout<<v[i]<<" ";
}
cout<<endl;
}
else{
vector<ll> res;
ll e=0,o=0;
for(ll i=0;i<n;i++){
if(i&1!=0){
res.push_back(even[e]);
e++;
}
else{
res.push_back(odd[o]);
o++;
}
}
for(ll i=0;i<n;i++){
cout<<res[i]<<" ";
}
cout<<endl;
}
}
int main() {
ll t=1;
cin>>t;
while(t--){solve();}
return 0;
}
Your first case
Is correct.
But, I don’t think rest of solution is correct. If (odd.size () & 1) != 0
(which means there are odd number of odd parity elements in the array) the array need not be lovely. Consider following array
3 3 2 3
Also, why should printing odd and even alternatively do the job (in that last case) ?
NOTE : (a & b != 0)
is equivalent to a & (b != 0)
because of the operator precedence and I have assumed that you didn’t mean what you coded there.
P.S Please do explain your thought process as it can help others.