C++ code to find card spread way to make all sum equal for each player


Suppose we have an array A with n elements. Here n is even. A[i] is a number written on ith card. There are n/2 people who want to play a game. At the beginning, each player will take two cards. We have to find the way to distribute cards in such a way that sum of values written on the cards will be same for each player.

So, if the input is like A = [1, 5, 7, 4, 4, 3], then the output will be [(0, 2), (5, 1), (3, 4)], because A[0] + A[2] = 8, A[5] + A[1] = 8 and A[3] + A[4] = 8.

Steps

To solve this, we will follow these steps −

n := size of A
Define one array of pairs p of size n
for initialize i := 0, when i < n, update (increase i by 1), do:
   first element of p[i] := A[i]
   second element of p[i]:= i
sort the array p, p + n
for initialize i := 0, when i < n / 2, update (increase i by 1), do:
   print second element of p[i] and second element of p[n - i - 1]

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A){
   int n = A.size();
   pair<int, int> p[n];
   for (int i = 0; i < n; i++){
      p[i].first = A[i];
      p[i].second = i;
   }
   sort(p, p + n);
   for (int i = 0; i < n / 2; i++)
      cout << "(" << p[i].second << ", " << p[n - i - 1].second <<"), ";
}  
int main(){
   vector<int> A = { 1, 5, 7, 4, 4, 3 };
   solve(A);
}

Input

{ 1, 5, 7, 4, 4, 3 }

Output

(0, 2), (5, 1), (3, 4),

Updated on: 15-Mar-2022

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements