In this HackerEarth Eating apples problem solution You are staying at point (1,1) in a matrix 10^9 x 10^9. You can travel by following these steps:

If the row where you are staying has 1 or more apples, then you can go to another end of the row and can go up.
Otherwise, you can go up.
The matrix contains N apples. The ith apple is at point (xi,yi). You can eat these apples while traveling. 

For each of the apples, your task is to determine the number of apples that have been eaten before.


HackerEarth Eating apples problem solution


HackerEarth Eating apples problem solution.

#include<bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ins insert
#define all(v) v.begin(),v.end()
#define sz(v) (int)v.size()
#define up_b upper_bound
#define low_b lower_bound
#define rep(i,a,b) for(ll i=a;i<=b;i++)
#define rev(i,a,b) for(int i=b;i>=a;i--)
#define boost ios_base::sync_with_stdio(NULL),cin.tie(NULL),cout.tie(NULL)
#define nl '\n'

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,int> pli;
typedef pair<int,ll> pil;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<pii> vii;

const int N=100001;
const int MXN=1000001;

pair<pii,int> a[N];

int ans[N];

int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].x.x>>a[i].x.y;
a[i].y=i;
}
sort(a+1,a+n+1);
int d=0;
int cnt=0;
for(int i=1;i<=n;i++){
int j=i;
while(j<n&&a[j].x.x==a[j+1].x.x)j++;
if(d==0){
for(int k=i;k<=j;k++){
ans[a[k].y]=cnt;
cnt++;
}
}
else{
for(int k=j;k>=i;k--){
ans[a[k].y]=cnt;
cnt++;
}
}
d=1-d;
i=j;
}
for(int i=1;i<=n;i++){
cout<<ans[i]<<nl;
}
}

Second solution

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

const int maxn = 1e6 + 14;
map<int, vector<pair<int, int> >> mp;
int ans[maxn];
int main(){
ios::sync_with_stdio(0), cin.tie(0);
int n;
cin >> n;
for(int i = 0; i < n; i++){
int x, y;
cin >> x >> y;
mp[x].push_back({y, i});
}
bool rev = false;
int sz = 0;
for(auto [x, vec] : mp){
if(rev)
sort(vec.begin(), vec.end(), greater<pair<int, int> >());
else
sort(vec.begin(), vec.end());
for(auto [y, i] : vec)
ans[i] = sz++;
rev ^= 1;
}
for(int i = 0; i < n; i++)
cout << ans[i] << '\n';
}