#include <bits/stdc++.h>
#include <fstream>
#define vi vector<int>
#define pi pair<int, int>
#define vs vector<string>
#define mp make_pair
#define mi map<int, int>
#define ull unsigned long long int
#define fo(i, k, n) for(int i = k; i < n; i++)
#define pqi priority_queue<int>
#define ll long long int
#define pb push_back
#define mod 1000000007
#define INF 1e18
#define f first
#define s second
using namespace std;
bool sortcmp(pi a, pi b){
if(a.f == b.f){
return a.s < b.s;
}
return a.f > b.f;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while(t--){
int n, k;
cin >> n >> k;
int a[n];
for(int i = 0; i < n; i++) cin >> a[i];
vi bcount(31, 0);
for(int i = 0; i < n; i++){
for(int j = 0; j <= 30; j++){
if(a[i] & (1 << j)) bcount[j]++;
}
}
vector<pi> cz(31);
for(int i = 0; i <= 30; i++){
cz[i] = mp(pow(2, i)*bcount[i], i);
}
sort(cz.begin(), cz.end(), sortcmp);
int ans = 0;
for(int i = 0; i < k; i++){
ans = ans|(1 << (cz[i].s));
}
cout << ans << "\n";
}
return 0;
}
This code passes the second sub-task but fails the first sub-task.
Can someone provide a case where the above solution fails?
But, I printed all the values of the vector and saw them. They were 0. Also, 2 tc passed. I know that it is necessary to initialize. But it didn’t take some garbage value when I gave some custom input and ran on ide. So, any reason for this behaviour or it is something like that incident only when array is accessed out of bounds then its value at starting index changes? btw thanks @akshitm16
you have change a little in your function sortinrev as follow
bool sortinrev(const pair<lld,lld> &a,
const pair<lld,lld> &b)
{
if (a.first>b.first) return true; else if (a.first==b.first) return a.second<b.second;
return false;
}
this is so because if the contribution of two bits is same then we have to select lower bit.
Hope it helps:)
It is quite unpredictable but concrete for a particular input. If for input, garbage value is x, then everytime garbage value will be same x for this particular input but this x is unpredictable.