Saturday, 17 February 2018

Smaller than the element code in c++

https://www.codechef.com/CODR2018/problems/KRYP6/


#include <stdio.h>
#include <iostream>
#include <set>

using namespace std;
set <long long> st;
set <long long>::iterator ind;
int main() {
    long long n,i=0;
    scanf("%lld",&n);
    long long *a=(long long *)malloc(sizeof(long long)*n);
    for(i=0;i<n;i++)
        scanf("%lld",&a[i]);
    for(i=0;i<n;i++)
    {
        ind = st.lower_bound(a[i]);
   
if (ind == st.begin())
    printf("-1\n");
else {
    ind--;
    printf("%lld\n", *ind);
}
st.insert(a[i]);
    }
 
return 0;
}

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. We can understand the code better if we use insert and find functions in sets
    #include
    #include
    #include

    using namespace std;
    set st;
    set ::iterator ind;
    int main() {
    long long n,i=0;
    scanf("%lld",&n);
    long long *a=(long long *)malloc(sizeof(long long)*n);
    for(i=0;i<n;i++)
    scanf("%lld",&a[i]);
    for(i=0;i<n;i++)
    {
    st.insert(a[i]);
    ind = st.find(a[i]);

    if (ind == st.begin())
    printf("-1\n");
    else {
    ind--;
    printf("%lld\n", *ind);
    }

    }

    return 0;
    }

    ReplyDelete