KJCP3 - Editorial

PROBLEM LINK:

Take Turns

Practice
Contest

Author: Dipen Ved
Tester: Dipen Ved
Editorialist: Nirali

DIFFICULTY:

EASY

PREREQUISITES:

Use of iterators and sets

PROBLEM:

Given two lists, you have to sort them and print them alternatively starting with list one.

QUICK EXPLANATION:

The input is taken using two ‘sets’ and two ‘for loops’ for two lists. Take two iterators, each pointing to the beginning of the respective sets. Using a for loop, alternatively print the numbers the two iterators are pointing to.

EXPLANATION:

Let’s first consider solving the problem for a single test case. We are given two lists. We have to take the input using set so that they are already sorted and we don’t have to write a separate code again for sorting the list. So, using for loop and insert function -

for(int i=0;i<n;i++) { 
  int temp; 
  scanf("%d",&temp); 
  set1.insert(temp); 
}

Here, n is the size of the list and temp is the number in the list
Similarly, for the second list.
Now, we wish to print the elements of the lists alternatively starting with list one. So let’s put an iterator to point to the beginning to set2.

set<int>::iterator it2 = set2.begin();

We also want an iterator pointing to the start of set1, which we will do in the for loop.

for(set <int>::iterator it1 = set1.begin();it1!=set1.end() && it2!=set2.end();it1++,it2++) {
            cout<<*it1<<" "<<*it2<<" ";	        
}

The for loop will run till both the iterators reach the end of their respective sets and alternatively both sets will be printed.

AUTHOR’S AND TESTER’S SOLUTIONS:

Solution can be found here