732D. Exams - Codeforces Solution C++

  Problem Link : 732D. Exams 


✅ C++ Solution :

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

vector<int> v,days;
unordered_set<int> us;
bool func(int d,int m)
{
	us.clear();
	if(d<m)
		return 0;
	int req=0;
	int avl=d-m;
	int i=d;
	int prev=-1;
	for(;i>0;i--)
	{
		while(i>0 && (v[i]==0 || us.find(v[i])!=us.end()))
		{
			i--;
			avl--;
		}
		if(prev!=-1)
		{
			int p=prev-i-1;
			req-=min(req,p);
		}
		if(i==0)
		    break;
		us.insert(v[i]);
		req+=days[v[i]];
		if(req>avl)
			return 0;
		prev=i;

	}

	if(req>avl)
		return 0;

	return 1;
}

int main()
{
	int n,m,d,p;
	cin>>n>>m;
	
	v.clear();
	days.clear();
	v.push_back(-1);
	for(int i=1;i<=n;i++)
	{
		cin>>d;
		v.push_back(d);
	}
	days.push_back(0);
	for(int i=1;i<=m;i++)
	{
		cin>>p;
		days.push_back(p);
	}

	int low=0,high=n,mid;

	while(low<high)
	{
		mid=low+(high-low)/2;

		if(func(mid,m))
			high=mid;
		else
			low=mid+1;
	}

	if(func(low,m))
		cout<<low;
	else
		cout<<"-1";


}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!