lundi 16 novembre 2020

How to solve odd and even position element in c++? [closed]

Write a program to sort the elements in odd positions in descending order and elements in even position in ascending order in c++

Input Format

First line of input contains test case 't' Next 't' lines contains array of numbers

Constraints

1<=t<=30

Output Format

Output contains sorted array for 't' test cases

Sample Input 0

1 13 2 4 15 12 10 5

Sample Output 0

15 2 13 4 12 5 10

Anyone Help to solve this i'm partially understand the problem

#include <bits/stdc++.h>
using namespace std;
#define For(it, val, n) for (int it = val; it < n; it++)

void solve()
{
  string s = " ";
  int count = 0;

  getline(cin, s);
  while (s.length() == 0)
  {
    getline(cin, s);
  }
  istringstream input(s);
  vector<int> result;
  int value;
  while (input >> value)
  {
    result.push_back(value);
  }
  const bool success = input.eof();
  vector<int> odd;
  vector<int> even;
  vector<int> ans;
  int o = 1;
  int e = 0;
  for (int i = 0; i < result.size(); i++)
  {
    if (result[i] & 1)
    {
      odd.push_back(result[i]);
    }
    else
    {
      even.push_back(result[i]);
    }
  }

  sort(odd.rbegin(), odd.rend());
  sort(even.begin(), even.end());
  int os = odd.size();
  int es = even.size();
  int temp=min(os,es);
  for(int i=0;i<temp;i++)
  {
ans.push_back(odd[i]);
ans.push_back(even[i]);
  }
 int it=result.size()-temp;
   for(int i=it-1;i<result.size();i++)
  {

ans.push_back(even[i]);
  }
  for(auto i:ans) cout<<i<<" ";
}
int main()
{
  ios::sync_with_stdio(0);
  cin.tie(0);
  int T;
  cin >> T;

  while (T--)
  {

    solve();
  }
}

Aucun commentaire:

Enregistrer un commentaire