HackerEarth: Kinako Bread (DS- Greedy, 2 pointers )


HackerEarth: Kinako Bread (DS- Greedy, 2 pointers )


///==================================================///
/// HELLO WORLD !! ///
/// IT'S ME ///
/// BISHAL GAUTAM ///
/// [ bsal.gautam16@gmail.com ] ///
///==================================================///
#include<bits/stdc++.h>
#define X first
#define Y second
#define mpp make_pair
#define nl printf("\n")
#define SZ(x) (int)(x.size())
#define pb(x) push_back(x)
#define pii pair<int,int>
#define pll pair<ll,ll>
///---------------------
#define S(a) scanf("%d",&a)
#define P(a) printf("%d",a)
#define SL(a) scanf("%lld",&a)
#define S2(a,b) scanf("%d%d",&a,&b)
#define SL2(a,b) scanf("%lld%lld",&a,&b)
///------------------------------------
#define all(v) v.begin(),v.end()
#define CLR(a) memset(a,0,sizeof(a))
#define SET(a) memset(a,-1,sizeof(a))
#define fr(i,a,n) for(int i=a;i<=n;i++)
using namespace std;
typedef long long ll;
///==========CONSTANTS=============///
/// Digit 0123456789012345678 ///
#define MX 100005
#define inf 1000000010
#define MD 1000000000LL
#define eps 1e-9
///===============================///

vector<int>v[MX+2];
int L[MX+2],R[MX+2];
int c1[MX+2],c2[MX+2];///Connections- Least connection & Most connections;
set<pii>sl,sr;/// storing current indices of Least & most for every elements

ll Calc( ) {
int rgBg=(*sr.begin()).X;
int lfEd=(*sl.rbegin()).X;
return (rgBg-lfEd);
}
int s[MX+2];
int ar[MX+2];
int main() {
int tc,cs=1,i,j,k,q,n,m,x,y;
//S(tc);
tc=1;
while(tc--) {
S2(n,m);
fr(i,1,m)v[i].clear();
fr(i,1,n) {
S(x);
ar[i]=x;
v[ x ].pb( i );
}
fr( i,1,m ) {
S2( L[i],R[i] );
R[i]++;
}
int i,f=1;
sl.clear();
sr.clear();
CLR(s);/// s-arry for tot times 'i' has been taken
/// Pre;
for(i=1; i<=m; i++) {
int sz=SZ( v[i] );
if( L[i]+s[i]>sz ) {
f=0;
break;
} else c1[ i ]=v[i][ L[i]+s[i]-1 ];
if( R[i]+s[i]>sz ) {
c2[i]=n+1;
} else c2[i]=v[i][ R[i]+s[i]-1];
sl.insert( mpp( c1[i],i ) );
sr.insert( mpp( c2[i],i ) );
s[i]++;
}
if(f==0) {
printf("0\n");
continue;
}
ll tp=max( Calc( ),0LL );
/// Now, Procedure of deleting from last;
ll sm=tp;
int j=1;
while(j<=n) {
i=ar[j];
///Del ar[i] && update latest info for ar[i];
sl.erase( mpp( c1[i],i ) );
sr.erase( mpp( c2[i],i ) );
int sz=SZ( v[i] );
if( L[i]+s[i]>sz ) {
break;
} else c1[ i ]=v[i][ L[i]+s[i]-1 ];
if( R[i]+s[i]>sz ) {
c2[i]=n+1;
} else c2[i]=v[i][ R[i]+s[i]-1];
sl.insert( mpp( c1[i],i ) );
sr.insert( mpp( c2[i],i ) );
s[i]++;
ll tp=Calc();
sm+=max( tp,0LL );
j++;
}
printf("%lld\n",sm);
}
return 0;
}

Comments

Popular posts from this blog

HackerEarth: City and Campers 2 (DSU-UnionFind)

Two Pointers Technique & Binary Search For Beginners

Problem : Codeforces Round #406 (Div. 1) B [ Legacy ]( Dijakstra, Segment tree)