# Output Contest Matches in C++

Suppose we have n teams and we always arrange the rather strong team to play with the rather weak team, like make the rank 1 team play with the team with rank n, this strategy is to make the contest more interesting. Now we have to find their final contest matches in the form of a string.

These teams are given in the form of positive integers from 1 to n, which represents their initial rank. So, rank 1 is the strongest team, and Rank n is the weakest team. We will use parentheses and commas to represent the contest team pairing - parentheses ('(‘, ')') for pairing and commas (',') for partition. During the pairing process in each round, we always have to follow the strategy of making the rather strong one pair with the rather weak one.

So, if the input is like 4, then the output will be ((1,4), (2,3))

To solve this, we will follow these steps −

• Define a function create(), this will take low, high, array v2, array v1,

• if low >= high, then −

• return

• insert "(" concatenate v1[low] concatenate ", " concatenate v1[high] concatenate ") at the end of v2

• create(low + 1, high - 1, v2, v1)

• From the main method do the following −

• Define arrays v1, v2

• for initialize i := 1, when i <= n, update (increase i by 1), do −

• insert convert i to string at the end of v1

• while size of v1 > 1, do −

• create(0, size of v1, v2, v1)

• v1 := v2

• clear the v2 array

• return last element of v1

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void create(int low, int high, vector <string>& v2, vector <string>& v1){
if (low >= high)
return;
v2.push_back("(" + v1[low] + "," + v1[high] + ")");
create(low + 1, high - 1, v2, v1);
}
string findContestMatch(int n) {
vector v1, v2;
for (int i = 1; i <= n; i++) {
v1.push_back(to_string(i));
}
while (v1.size() > 1) {
create(0, v1.size() - 1, v2, v1);
v1 = v2;
v2.clear();
}
return v1.back();
}
};
main(){
Solution ob;
cout << (ob.findContestMatch(4));
}

## Input

4

## Output

((1,4),(2,3))

Updated on: 16-Nov-2020

119 Views