Skip to content

Commit 0bd0b7f

Browse files
committed
Recent problem from Codechef that uses Hashing
1 parent c947ab6 commit 0bd0b7f

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Hashing/chef_and_subarrays.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
3+
Problem Link - https://www.codechef.com/COOK129C/problems/CSUBS
4+
5+
Problem Statement - Chef is playing a game where he has an array A of N integers, and an integer K. He looks at every subarray of length K, and writes its sum on a piece of paper. If a number appears as the sum of multiple subarrays of length K, then he only writes down that number once.
6+
7+
Chef is lazy and doesn't like to write numbers. You, being a friend of Chef, want to modify the array such that Chef will only write one number on his paper. In one modification you can choose any index i
8+
and replace A[i] with any integer.
9+
10+
You need to find the minimum number of modifications required.
11+
12+
*/
13+
14+
#include<bits/stdc++.h>
15+
#define int long long
16+
17+
using namespace std;
18+
19+
void solve(int n, int k, vector<int> v){
20+
int ans = 0;
21+
for(int i=0; i<k; i++){
22+
int maximumOccurence = 0;
23+
map<int, int> ma;
24+
for(int j=i; j<n; j += k){
25+
maximumOccurence++;
26+
ma[v[j]]++;
27+
}
28+
int cur = maximumOccurence-1;
29+
for(auto ele:ma){
30+
cur = min(cur, maximumOccurence-ele.second);
31+
}
32+
ans += cur;
33+
}
34+
cout<<ans<<"\n";
35+
}
36+
37+
signed main(){
38+
ios::sync_with_stdio(false);cin.tie(0);
39+
int t = 1;
40+
cin >> t;
41+
for(int i=1; i<=t; i++){
42+
int n,k;
43+
cin>>n>>k;
44+
vector<int> v(n+1);
45+
for(int j=1; j<=n; j++){
46+
cin>>v[j];
47+
}
48+
solve(n,k,v);
49+
}
50+
return 0;
51+
}
52+
53+
// Tutorial Link to understand the solution - https://discuss.codechef.com/t/csubs-editorial/90045

0 commit comments

Comments
 (0)