Editorial 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

CPTHON-4

Conducted on: 22th Feb, 2024

Time: 10:00 pm to 11:00 pm

Topics: Array, Bit Manipulation, Matrices

Crime Creek Village


In a village with a high risk of theft, villagers have decided to ensure safety by constructing
their houses continuously. The village is circular in fashion where the last house is next to the
first house. Some houses are empty while others are occupied. Villagers plan to relocate to
the empty houses in order to maintain continuity. Each relocation incurs a unit cost. The
villagers aim to minimize their overall cost while increasing the safety of their village. Would
you like to help them in minimizing their cost?

Input Format:
The first line of the input contains an integer N, representing the total number of houses in
the village.
Next line consists of N space-separated integers(0 or 1), where 0 represents an empty house
and 1 represents house with people.

Constraints:

1<=N<=1e6
A[i] is either 0 or 1.

Output Format:
A single integer, representing the minimum cost.
Sample Input 0
7
0101100

Sample Output 0
1

Explanation 0
Relocate the house located at index 1 to index 2, resulting in the arrangement of houses as
follows: 0 0 1 1 1 0 0(Assuming 0-based indexing)

Sample Input 1
9
011100110

Sample Output 1
2

Explanation 1
Swap the positions of the house at index 3 with the house at index 0, and also relocate the
house at index 6 to index 8. Consequently, the arrangement of houses will be [1 1 1 0 0 0 0 1
1].(Assuming 0-based indexing)

Approach:
We can use the Sliding Window and two pointers approach to solve this problem efficiently.
The idea is to consider a window size equal to the number of 1's in the array, as we need to
ensure that all 1's are placed together.
Count 1's: Start by counting the number of 1's in the array. This count will determine the size
of the window we'll use.

Sliding Window Technique


1. Initialize two pointers, let's call them start and end, to define the window.
2. Move the window across the array:
3. For each window, count the number of 1's within that window.
4. Calculate the number of 0's (empty houses) in the window by subtracting the count of 1's
from the window size.
5. The goal is to minimize the number of 0's within each window, as these represent the
number of swaps needed to bring all 1's together.

Minimum Swaps: Among all the windows, find the window with the minimum number of 0's.
This window represents the optimal arrangement where the least number of swaps are
needed to bring all 1's together.
Output: Return the count of 0's in the window with the minimum number of 0's. This count
represents the minimum number of operations required to achieve the desired arrangement.
By following this approach, we can efficiently identify the minimum number of swaps
required to make all 1's continuous in a circular array.

Time Complexity: O(N)


Space Complexity: O(1)

Code:

#include<iostream>
using namespace std;
int minSwaps(vector<int>& nums) {
int n = nums.size();
int total_ones = 0;
for(int i = 0;i < n;i++){
total_ones += nums[i];
}
int i = 0;
int j = total_ones-1;
int sum = 0;
for(int k = i;k <= j;k++){
sum += nums[k];
}
int ans = sum;
while(i<n){
ans = max(ans,sum);
sum -= nums[i];
i++;
j = (j+1)%n;
sum += nums[j];
}
return total_ones-ans;
}
int main(){
int n;
cin>>n;
vector<int>vec(n);
for(int i = 0;i < n;i++){
int x;
cin>>x;
vec[i] = x;
}
int ans = minSwaps(nums);
cout<<ans<<endl;
}
Construct the balanced team
In preparation for an inter-college event, your college has entrusted you with the
responsibility of forming a team. The task involves meticulously selecting one student from
each branch to construct a team that minimizes the difference between the highest and
lowest skill scores, referred to as the "balance difference." The provided data is an n*m
matrix named "score," where n signifies the number of branches in your college, and m
represents the consistent number of students per branch(assume all branches have the same
strength).

Each element score[i][j] within the matrix denotes the skill score of the jth student belonging
to the ith branch. Your task is to utilize this information and generate a team that achieves
the smallest possible balance difference and print that difference.

Input Format
The initial line of input comprises two integers, namely n and m, representing the number of
branches in the college and the consistent number of students per branch, respectively.
Subsequently, the following n lines contain m space-separated integers, each line providing
the skill scores of students within the respective branches.

Constraints
1<=N, M<=500
1<=score[i][j]<=1000000

Output Format
The output comprises a single integer, representing the minimum computed balance
difference achieved by the algorithm in selecting and forming the team.

Sample Input 0
33
123
456
789

Sample Output 0
1

Explanation 0
You can choose the students with the skill 3, 3, and 4 from the 1st, 2nd and 3rd branch
respectively (assuming 1-based indexing). Hence the minimum balanced difference is 4 - 3 = 1

Approach:
The main idea is to maintain a set which stores elements from different arrays along with
their array index and position in the array that keeps track of the current smallest range. The
algorithm iteratively updates the range by moving the pointers within the arrays and
considering the minimum difference between the current maximum and minimum values.
The set is used to efficiently identify the array and index of the next element to be considered
for the range.

Time Complexity: O(N x M logM)


Space Complexity: O(N)
Code:

#include <bits/stdc++.h>
using namespace std;
int minimumDifference(int N, int M, vector<vector<int>> &arr)
{
// sort each individual row
for (auto &it : arr)
{
sort(it.begin(), it.end());
}
set<pair<int, pair<int, int>>> s;
for (int i = 0; i < N; i++)
{
s.insert({arr[i][0], {i, 0}});
}
int min_diff = INT_MAX;
while (s.size() == N)
{
auto it = s.begin();
// get the minimum skill score of the current team
int min_score = it->first;
auto itr = --s.end();
// get the maximum skill score of the current team
int max_score = itr->first;
int row = it->second.first;
int col = it->second.second;
s.erase(s.begin());
if (col + 1 < M)
{
s.insert({arr[row][col + 1], {row, col + 1}});
}
min_diff = min(min_diff, max_score - min_score);
}
return min_diff;
}
int main()
{
int n, m;
cin >> n >> m;
vector<vector<int>> score(n, vector<int>(m));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> score[i][j];
}
}
cout << minimumDifference(n, m, score) << endl;
return 0;
}

Maximum Friendship Score


There are some people living in a town. Each person is having an id associated with them.
Two people are good friends if their friendship score is high. The friendship score of two
people is calculated by taking their id's and dividing it into the sum of power of 2's(5 can be
divided into an array [4,1]) and then take the sum of intersecting elements of both the arrays.
For example,people having id's 7 and 9 have a friendship score of 1. Find the maximum
possible friendship score.

Input Format
The first line of the input contains an integer N, representing the number of people living in a
town.
Next line contains N space separated integers, representing the id of each person.

Constraints
1 ≤ N ≤ 1e5
1 ≤ A[i] ≤ 1e5

Output Format
Return a single integer representing the maximum possible friendship score.
Sample Input 0
4
4 8 12 16

Sample Output 0
8

Explanation 0
Friendship of 1st and 2nd person is maximum, assuming the 0-based indexing.

Sample Input 1
4
4 8 16 2

Sample Output 1
0
Time Complexity: O(32 x N) or O(N logN)
Space Complexity: O(1)

Explanation & Code:


The main observation in this question is that the answer is nothing but the maximum AND
value of any two person id.
e.g if we take two values say 8 and 12.
9 can be written as => 1000 (2^3 + 2^0) whereas 12 can be written as => 1100 (2^3+2^2).
Now the sum of the intersection of these values are nothing but 2^3 which is equivalent to
(9)&(12).So the question boils down to calculate the maximum AND possible.

*Follow the steps mentioned below to implement the approach:*


Create a variable res to store the final answer.
Traverse a loop from 31 to 0 to see if there are more than one elements in the array whose
AND with res equals res if we add the current bit to res and keep updating res.
Return res as the final answer

#include <bits/stdc++.h>
using namespace std;

// Utility function to check number of elements


// having set msb as of pattern
int checkBit(int pattern, int arr[], int n)
{
int count = 0;
for (int i = 0; i < n; i++)
if ((pattern & arr[i]) == pattern)
count++;
return count;
}

int maxAND(int arr[], int n)


{
int res = 0, count;

// iterate over total of 32bits from msb to lsb


for (int bit = 31; bit >= 0; bit--) {
// find the count of element having same pattern as
// obtained by adding bits on every iteration.
count = checkBit(res | (1 << bit), arr, n);

// if count >= 2 set particular bit in result


if (count >= 2)
res = res | (1 << bit);
}
return res;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<maxAND(arr, n);
return 0;

You might also like