Hackearth's Data Structures solutions( SnackDown Contest, Mark The Answer, Most Frequent ) :
Problem 16: SnackDown Contest
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long t;
cin>>t;
while(t--)
{
long long n,p,q,i;
cin>>n;
cin>>p;
vector<long long>v1(p,0);
for(i=0;i<p;i++)
{
cin>>v1[i];
}
cin>>q;
vector<long long>v2(q,0);
for(i=0;i<q;i++)
{
cin>>v2[i];
}
vector<long long>v3(p+q);
merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v3.begin()); //vector v3=v1+v2
set<long long>s(v3.begin(),v3.end()); //converting vector v3 into set
long long test=1;
for(auto &e:s) //set traversal , see note below
{
if(e==test)
{
test++;
}
}
if(test==n+1)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
}
The advantage of converting merged vector v3 into set s is that it removes all the duplicate elements (helps when there's a question which can be solved by both) and also sort the elements.
So now we have to check only if the elements of the set forms a proper counting up to n , if they do that means all questions can be solved by them and if there's a discontinuity that means there's a question which can't be solved by both of them.
Problem 17: Mark The Answer
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n,x,e,count=0,ct2=0; //e=element , n=no. of elements , ct2=count2
cin>>n>>x;
while(n--)
{
cin>>e;
if(e<=x)
{
count++;
}
else
{
ct2++;
if(ct2==2)
{
break;
}
}
}
cout<<count;
}
This code is simple. There's no need for any explanation.
Problem 18: Most Frequent
Solution: (in c++)
( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)
#include<bits/stdc++.h>
using namespace std;
int main()
{
map<int,int>m;
int n,i,p=0,q;
cin>>n;
int a[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(auto &e:m) //map traversal
{
if(e.second>p)
{
p=e.second;
q=e.first;
}
}
cout<<q;
}
Comments
Post a Comment