C++ program to distribution of apples for two mice

Suppose we have a number n and two arrays A and B of different sizes. There are two mice: m1 and m2. We put n apples in front of them. We know which apples m1 likes. Similarly, we also know which apples m2 likes. We do not want any conflict between the mice (as they may like the same apple), so we decided to distribute the apples between the mice on our own. We are going to give some apples to m1 and some apples to m2. It doesn't matter how many apples each mouse gets but it is important that each mouse gets only the apples it likes. It is also possible that somebody doesn't get any apples. A[i] holds the apples that m1 likes and B[i] are apples which are liked by m2. We have to print how we distribute them.

Problem Category

An array in the data structure is a finite collection of elements of a specific type. Arrays are used to store elements of the same type in consecutive memory locations. An array is assigned a particular name and it is referenced through that name in various programming languages. To access the elements of an array, indexing is required. We use the terminology 'name[i]' to access a particular element residing in position 'i' in the array 'name'. Various data structures such as stacks, queues, heaps, priority queues can be implemented using arrays. Operations on arrays include insertion, deletion, updating, traversal, searching, and sorting operations. Visit the link below for further reading.


So, if the input of our problem is like n = 4; A = [1, 2]; B = [2, 3, 4], then the output will be [1, 1, 2, 2]


To solve this, we will follow these steps −

Define an array v of size: n and fills with 0
for initialize i := 0, when i < size of A, update (increase i by 1), do:
   j := A[i]
   increase v[j - 1] by 1
for initialize i := 0, when i < n, update (increase i by 1), do:
   (if v[i] is same as 1, then print "1, ", otherwise print "2, ")


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(int n, vector<int> A, vector<int> B){
   int v[n] = { 0 };
   for (int i = 0; i < A.size(); i++){
      int j = A[i];
      v[j - 1]++;
   for (int i = 0; i < n; i++){
      (v[i] == 1) ? cout << "1, " : cout << "2, ";
int main(){
   int n = 4;
   vector<int> A = { 1, 2 };
   vector<int> B = { 2, 3, 4 };
   solve(n, A, B);


4, { 1, 2 }, { 2, 3, 4 }


1, 1, 2, 2,