1684F - Diverse Segments - CodeForces Solution


data structures two pointers *2600

Please click on ads to support us..

C++ Code:

#include<iostream>
#include <map>
#include <vector>
using namespace std;
int t,n,m;
map<int,vector<int>> h;
int main(){
	cin>>t;
	while(t--){
	cin>>n>>m;
	vector<int> a(n+1),l(n+1,n+1),mxl(n+1,n+1);
	int x,y,ans=n,st=n+1,en=0,minL=n+1;
	h.clear();
	for(int i=1;i<=n;i++){
		cin>>a[i];
		h[a[i]].push_back(i);
	}
	for(int i=0;i<m;i++){
		cin>>x>>y;
		l[y]=min(l[y],x);
	}
	for(int i=n;i>0;i--){
		minL=min(minL, l[i]);
		vector<int> *tmp=&h[a[i]];
		tmp->pop_back();
		int len=tmp->size();
		if (minL<i){
			int la=len?tmp->at(len-1):-1;
			if (minL<=la){
				en=max(la, en);
				vector<int>::iterator it=lower_bound(tmp->begin(),tmp->end(),minL);
				mxl[i-1]=*it;
				++it;
				st=min(st,(*it?*it:i));
			}
		}
	}
	for(int i=n;i>=en;i--){
		st=min(st, mxl[i]);
		ans=min(ans,max(0,i-st+1));
	}
	cout<<ans<<endl;	}
}


Comments

Submit
0 Comments
More Questions

437. Path Sum III
436. Find Right Interval
435. Non-overlapping Intervals
406. Queue Reconstruction by Height
380. Insert Delete GetRandom O(1)
332. Reconstruct Itinerary
368. Largest Divisible Subset
377. Combination Sum IV
322. Coin Change
307. Range Sum Query - Mutable
287. Find the Duplicate Number
279. Perfect Squares
275. H-Index II
274. H-Index
260. Single Number III
240. Search a 2D Matrix II
238. Product of Array Except Self
229. Majority Element II
222. Count Complete Tree Nodes
215. Kth Largest Element in an Array
198. House Robber
153. Find Minimum in Rotated Sorted Array
150. Evaluate Reverse Polish Notation
144. Binary Tree Preorder Traversal
137. Single Number II
130. Surrounded Regions
129. Sum Root to Leaf Numbers
120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees