Header Ad

HackerEarth Little Shino and Pairs problem solution

In this HackerEarth Little Shino and Pairs problem solution we have given a permutation of numbers from 1 to N. Among all the subarrays, find the number of unique pairs (a,b) such that a != b and a is maximum and b is the second maximum in that subarray.


HackerEarth Little Shino and Pairs problem solution


HackerEarth Little Shino and Pairs problem solution.

#include <bits/stdc++.h>

#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define be begin()
#define en end()
#define all(x) (x).begin(),(x).end()
#define alli(a, n, k) (a+k),(a+n+k)
#define REP(i, a, b, k) for(__typeof(a) i = a;i < b;i += k)
#define REPI(i, a, b, k) for(__typeof(a) i = a;i > b;i -= k)
#define REPITER(it, a) for(__typeof(a.begin()) it = a.begin();it != a.end(); ++it)

#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash
#define norm asdfasdgasdgsd
#define have adsgagshdshfhds

#define eps 1e-6
#define pi 3.141592653589793

using namespace std;

template<class T> inline T gcd(T x, T y) { if (!y) return x; return gcd(y, x%y); }
template<class T> inline T mod(T x) { if(x < 0) return -x; else return x; }

typedef vector<int> VII;
typedef vector<ll> VLL;
typedef pair<int, int> PII;
typedef vector< pair<int, int> > VPII;
typedef vector< pair<int, PII > > VPPI;

const int MOD = 1e9 + 7;
const int INF = 1e9;

int main(int argc, char* argv[])
{
if(argc == 2 or argc == 3) freopen(argv[1], "r", stdin);
if(argc == 3) freopen(argv[2], "w", stdout);
ios::sync_with_stdio(false);
int n, ans = 0, a;
stack <int> stk;
cin >> n;
REP(i, 0, n, 1)
{
cin >> a;
while(!stk.empty() and a > stk.top())
{
stk.pop();
ans++;
}
if(!stk.empty()) ans++;
stk.push(a);
}
cout << ans << endl;
return 0;
}

Second solution

#include <bits/stdc++.h>

using namespace std;

int N;
pair<int, int> A[100000];

int main()
{
scanf("%d", &N);
for(int i=0; i<N; i++)
scanf("%d", &A[i].first), A[i].second=i;
sort(A, A+N, greater<pair<int, int>>());
int a=A[0].second, b=A[0].second;
int ans=0;
for(int i=1; i<N; i++)
{
int x=A[i].second;
if(x<a || x>b)
ans++;
else
ans+=2;
a=min(a, x);
b=max(b, x);
}
printf("%d\n", ans);
return 0;
}

Post a Comment

0 Comments