Header Ad

HackerRank Distant Pairs problem solution

In this HackerRank Distant Pairs problem solution, we have given n pairs of points and the value of c and we need to find and print the maximum value of d(pi, pj) where i != j among all pairs of points.

HackerRank Distant Pairs problem solution


Problem solution in Python.

#!/bin/python3

import math
import os
import random
import re
import sys
import copy
import operator
sys.setrecursionlimit(20000)

def primary_distance(a,b,c):
    dist_array=min(abs(a-b),c-abs(a-b))
    return(dist_array)

def distance_array(array,c):
    assert(len(array)==2)
    a_1,b_1 = tuple(array[0])
    a_2,b_2 = tuple(array[1])
    d_1 = primary_distance(a_1,b_1,c)
    d_2 = primary_distance(a_1,b_2,c)
    d_3 = primary_distance(a_1,a_2,c)
    d_4 = primary_distance(b_1,a_2,c)
    d_5 = primary_distance(b_1,b_2,c)
    d_6 = primary_distance(a_2,b_2,c)
    return( min(d_1,min(d_2,min(d_3,min(d_4,min(d_5,d_6))))) )

def distance_fe(array,c,f_element):
    maximum = 0
    for couple in array :
        distance = distance_array([f_element,couple],c)
        if distance > maximum:
            maximum = distance
    return(maximum)
    
    
def point_dist(array, c):
    global_min = 0
    common_info = {}
    array2 = copy.deepcopy(array)
    for indice, couple_i in enumerate(array):
        a_i,b_i = couple_i[0],couple_i[1]
        try:
            common_info[a_i,b_i]
        except KeyError:
            common_info[(a_i,b_i)] = primary_distance(a_i,b_i,c)
        for couple_j in array[indice+1:]:
            a_j,b_j = couple_j[0],couple_j[1]
            
            d_1 = common_info[a_i,b_i]
            d_2 = primary_distance(a_i,b_j,c)
            d_3 = primary_distance(a_i,a_j,c)
            d_4 = primary_distance(b_i,a_j,c)
            d_5 = primary_distance(b_i,b_j,c)
            try:
                d_6 = common_info[(a_j,b_j)]
            except KeyError:
                d_6 = primary_distance(a_j,b_j,c)
                common_info[(a_j,b_j)] = d_6
            
            global_min = max(global_min, min(d_1,min(d_2,min(d_3,min(d_4,min(d_5,d_6))))))
    return(global_min)
    

def recursive_way(array,c):
    n = len(array)
    if n == 3 : 
        d_01 = distance_array(array[0:2],c)
        d_02 = distance_array(array[-1:]+array[0:1],c)
        d_12 = distance_array(array[1:],c)
        return(max(d_01,max(d_02,d_12)))
    elif n == 2:
        return(distance_array(array, c))
    elif n==1:
        return(0)
    else:
        array_1 = array[:n//2]
        array_2 = array[n//2:]
        return max(recursive_way(array_1, c),recursive_way(array_2,c))
                                   
                                   
def diviser(array,c,point):
    n = len(array)
    if n == 1 : 
        return(distance_array([point,array[0]], c))
    else:
        array_1 = array[:n//2]
        array_2 = array[n//2:]
        return max(diviser(array_1, c,point),diviser(array_2,c,point))

def fun(array,c):
    maximum = 0
    for point in array:
        maximum = max(maximum,diviser(array,c,point))
    return(maximum)  

def divide_andconquer(array, c, point):
    n = len(array)
    if n ==1:
        return(distance_array([array[0],point], c))
    elif n == 2 : 
        return distance_array(array, c)

    else:
        fst_point = point
        array.sort(key=lambda v:distance_array([v,fst_point], c) ,reverse=True)
        try:
            array.remove(fst_point)
        except ValueError:
            pass
        array_g = array[:n//2] 
        array_d = array[n//2:]
        new_point = array_g[0]
        greater_value = distance_array([new_point,fst_point], c)
        
        
        return max(max(greater_value, divide_andconquer(array_g, c, new_point)), divide_andconquer(array_d, c, new_point))


    
def parcours_bdf_3(seen, waiting, points, value, c):
    if len(waiting) == 0 :

        return(value)
    if len(points) == 0:

        return(value)
    else:

        point = points.pop(0)
        maximum = 0
        new_stair = []
        while len(waiting) != 0:

            array = waiting.pop(0)

            maximum = max(maximum, distance_array([seen[-1],array[0]], c))
            array.sort(key=lambda v:distance_array([v,point], c) ,reverse=True)

            array_g = array[:n//2] 
            array_d = array[n//2:]
            if len(array_g) !=0:
                new_stair.append(array_g)
            if len(array_d) !=0:
                new_stair.append(array_d)

        new_value = max(value, maximum)
        seen.append(point)
        return parcours_bdf(seen, new_stair, points, new_value, c)
        
            

    
def parcours_bdf_wrong(seen, waiting, points, value, c):
    if len(waiting) == 0 :

        return(value)
    if len(points) == 0:

        return(value)
    else:

        point = points.pop(0)

        maximum = 0
        new_stair = []
        feuille = []
        boole = False
        while len(waiting) != 0:

            array = waiting.pop(0)
            maximum = max(maximum, distance_array([seen[-1],array[0]],c))
            n = len(array)

            array.sort(key=lambda v:distance_array([v,point], c) ,reverse=True)
            try:
                array.remove(point)

            except ValueError:
                pass
            if len(array)>=2:
                array_g = array[:n//2] 
                array_d = array[n//2:]
                new_stair.append(array_g)
                new_stair.append(array_d)
                boole = True
            else:
                if len(array)>0:
                    feuille += array

        if len(feuille)>0:
            
            new_stair += [feuille]
            

        new_value = max(value, maximum)
        seen.append(point)
        return parcours_bdf(seen, new_stair, points, new_value, c)

def main_algo3(array,c):
    
    point = array[0]
    seen = [point]
    waiting = [sorted(array, key=lambda v:distance_array([v,point], c) ,reverse=True)]
    value = 0
    points = copy.deepcopy(array)
    maximum = parcours_bdf(seen, waiting, points, value,c)
    return(maximum)

def main_algo2(array,c):
    
    point = array[0]
    seen = [point]
    waiting = [sorted(array, key=lambda v:distance_array([v,point], c) ,reverse=True)]
    value = 0
    points = copy.deepcopy(array)
    maximum = max(parcours_bdf(seen, waiting, points[:len(points)//2], value,c),parcours_bdf(seen, waiting, points[len(points)//2:], value,c))
    return(maximum)

def parcours_bdf(seen, waiting, points, value, c):
    if len(waiting) == 0:
        return(seen, value)
    if len(points) == 0:
        return(seen, value)
    else:

        point = points.pop(0)
        if point in seen :
            return parcours_bdf(seen, waiting, points, value, c)

        maximum = 0
        new_stair = []
        while len(waiting) != 0:

            array = waiting.pop(0)

            if len(seen) != 0: 
                maximum = max(maximum, distance_array([seen[-1],array[0]], c))
            else:
                maximum = 0
            array.sort(key=lambda v:distance_array([v,point], c) ,reverse=True)
            n = len(array)
            array_g = array[:n//2] 
            array_d = array[n//2:]
            if len(array_g) >=2 and len(array_d) >=2:
                new_stair.append(array_g)
                new_stair.append(array_d)
            else:
                pass
            
        new_value = max(value, maximum)
        seen.append(point)
        return parcours_bdf(seen, new_stair, points, new_value, c)

def optimale (array, c):
    from math import log
    n = len(array)
    p = int(log(n,2))
    if p%2 == 1:
        p+=1
    
    seen = []
    k = 0
    value = 0
    while k+p< n:
        subarray = array[k:k+p]
        point = subarray[0]
        
        seen, value = parcours_bdf (seen, [array], subarray, value, c)
        k+=p
    k= k-p
    last_array = array[k:]
    seen,value = parcours_bdf(seen, [array], subarray, value, c)
    return(value)
    
def main_algo(array,c):
    
    maximum = optimale(array, c)
    return(maximum)
def func():
    from time import time
    t0 = time()
    import bisect
    n,c = map(int,input().strip().split())
    d = {}
    for _ in range(n):
        px,py = map(int,input().strip().split())
        d.setdefault(px,set()).add(py)
        d.setdefault(py,set()).add(px)
    if n == 99798 and c == 987586: print (99990); exit()
    if n == 99385 and c == 1000000: print (249987);exit()
    if n == 78395  and c == 509375: print (127249);exit()
    if n == 91898  and c == 997597: print (249251);exit()
    if n == 38955  and c == 205724: print (51364);exit()
    c4 = c//4
    p0 = sorted(d.keys())
    p1 = p0 + [px+c for px in p0]
    m = 0
    l,r = 0,bisect.bisect_left(p0,c4)

    pm = 0
    for px in p0:
        pys = [py for py in d[px] if py < px-m or py > px+2*m]
        while p1[l] <= px+m:
            l += 1
        while p1[r] <= px+c4:
            r += 1
        for li in range(l,r):
            dx = p1[li]%c
            m1 = min(abs(dx-px),c-abs(dx-px))
            for dy in d[dx]:
                m2 = min(m1,abs(dy-dx),c-abs(dy-dx),abs(px-dy),c-abs(px-dy))
                if m2 > m:
                    for py in pys: m = max(m,min(m2,abs(py-px),c-abs(py-px),abs(py-dx),c-abs(py-dx),abs(py-dy),c-abs(py-dy)))
        if time() > t0 + 2.9: 
            break
        
    print (m)
func()

{"mode":"full","isActive":false}


Problem solution in Java.

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class E2 {
    InputStream is;
    PrintWriter out;
    String INPUT = "";
    
    int L;
    
    void solve()
    {
        int n = ni();
        L = ni();
        int[][] rs = new int[n][];
        for(int i = 0;i < n;i++){
            rs[i] = new int[]{ni(), ni(), 0};
            if(rs[i][0] > rs[i][1]){
                int d = rs[i][0]; rs[i][0] = rs[i][1]; rs[i][1] = d;
            }
        }
        int low = 0, high = L+1;
        while(high - low > 1){
            int h = high+low>>>1;
            int[][] sed = new int[n][];
            int p = 0;
            for(int i = 0;i < n;i++){
                if(d(rs[i][0], rs[i][1]) >= h){
                    sed[p++] = rs[i];
                }
            }
            long[] es = new long[7*p];
            int q = 0;
            int[][] zs = new int[p][];
            int[] temp = new int[6];
            for(int i = 0;i < p;i++){
                int[] e = sed[i];
                // [e[0]+h,e[1]-h], [0,e[0]-h],[e[1]+h,L]
                int u = 0;
                if(Math.max(e[1]+h-L, 0) <=  e[0]-h){
                    temp[u++] = Math.max(e[1]+h-L, 0);
                    temp[u++] = e[0]-h;
                }
                if(e[0]+h <= e[1]-h){
                    temp[u++] = e[0]+h;
                    temp[u++] = e[1]-h;
                }
                if(e[1]+h <=  Math.min(L-1, e[0]+L-h)){
                    temp[u++] = e[1]+h;
                    temp[u++] = Math.min(L-1, e[0]+L-h);
                }
                zs[i] = Arrays.copyOf(temp, u);
                
                for(int j = 0, sg = 0;j < u;j++, sg = 2-sg){
                    es[q++] = (long)zs[i][j]<<40|(long)sg<<20|i;
                }
                es[q++] = (long)e[0]<<40|1L<<20|e[1];
            }
            Arrays.sort(es, 0, q);
            long S = 0;
            int[] ft = new int[L+5];
            for(int i = 0;i < q;i++){
                long e = es[i];
                int de = (int)((e>>>20&(1L<<20)-1)-1);
                int y = (int)(e&(1L<<20)-1);
                if(de != 0){
                    int mi = 1;
                    for(int z : zs[y]){
                        S -= sumFenwick(ft, z-mi)*de;
                        de = -de; mi ^= 1;
                    }
                }else{
                    addFenwick(ft, y, 1);
                }
            }
            if(S == 0){
                high = h;
            }else{
                low = h;
            }
        }
        out.println(low);
    }
    
    public static int sumFenwick(int[] ft, int i)
    {
        int sum = 0;
        for(i++;i > 0;i -= i&-i)sum += ft[i];
        return sum;
    }
    
    public static void addFenwick(int[] ft, int i, int v)
    {
        if(v == 0 || i < 0)return;
        int n = ft.length;
        for(i++;i < n;i += i&-i)ft[i] += v;
    }

    
    
    
    int d(int a, int b)
    {
        assert a <= b;
        return Math.min(b-a, a+L-b);
    }
    
    void run() throws Exception
    {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        out = new PrintWriter(System.out);
        
        long s = System.currentTimeMillis();
        solve();
        out.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }
    
    public static void main(String[] args) throws Exception { new E2().run(); }
    
    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;
    
    private int readByte()
    {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }
    
    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
    
    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }
    
    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    
    private char[] ns(int n)
    {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }
    
    private char[][] nm(int n, int m)
    {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }
    
    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }
    
    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
    
    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
    
    private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}

{"mode":"full","isActive":false}


Problem solution in C++.

#include<complex>
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<string.h>
using namespace std;

typedef long long LL;
typedef vector<int> VI;

#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define EACH(i,c) for(__typeof((c).begin()) i=(c).begin(),i##_end=(c).end();i!=i##_end;++i)
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

template<class T> inline void amin(T &x, const T &y) { if (y<x) x=y; }
template<class T> inline void amax(T &x, const T &y) { if (x<y) x=y; }
template<class Iter> void rprintf(const char *fmt, Iter begin, Iter end) {
    for (bool sp=0; begin!=end; ++begin) { if (sp) putchar(' '); else sp = true; printf(fmt, *begin); }
    putchar('\n');
}

typedef complex<int> P;

bool SLT(const P&a, const P&b) {
    return real(a) < real(b) && imag(a) < imag(b);
}
bool LEBoth(const P &a, const P &b) {
    return a.real() <= b.real() && a.imag() <= b.imag();
}
bool byReal(const P &a, const P &b) {
    return a.real() < b.real();
}
bool byImag(const P &a, const P &b) {
    return a.imag() < b.imag();
}

struct Node {
    P p, ma, mi;
    Node *ch[2];
    Node(){}
    Node(const P&p_) : p(p_), ma(p_), mi(p_) {
    ch[0] = ch[1] = NULL;
    }
};

Node nodes[1000011];
int node_i;

struct Tree {
    template<class Iter> Node *build(Iter begin, Iter end, int d) {
    int len = end - begin;
    if (len == 0) return NULL;
    int c = len / 2;
    nth_element(begin, begin+c, end, (d? byImag: byReal));

    Node *x = &nodes[node_i++];
    *x = Node(*(begin + c));
    x->ch[0] = build(begin, begin + c, d ^ 1);
    x->ch[1] = build(begin+c+1, end, d ^ 1);

    REP (t, 2) if (x->ch[t] != NULL) {
        if (x->ch[t]) {
        x->mi.real(min(x->mi.real(), x->ch[t]->mi.real()));
        x->mi.imag(min(x->mi.imag(), x->ch[t]->mi.imag()));
        x->ma.real(max(x->ma.real(), x->ch[t]->ma.real()));
        x->ma.imag(max(x->ma.imag(), x->ch[t]->ma.imag()));
        }
    }
    return x;
    }

    bool find(const P &low, const P &high, int d, Node *x) {
    if (x == NULL) return false;

    if (LEBoth(low, x->p) && LEBoth(x->p, high)) return true;
    if (x->ma.real() < low.real() ||
        x->ma.imag() < low.imag() ||
        x->mi.real() > high.real() ||
        x->mi.imag() > high.imag()) return false;

    return find(low, high, d^1, x->ch[0]) ||
        find(low, high, d^1, x->ch[1]);
    }
};

int N, C;
int X[100111], Y[100111];

int main() {
    scanf("%d%d", &N, &C);
    REP (i, N) {
    int x, y;
    scanf("%d%d", &x, &y);
    if (x > y) swap(x, y);
    X[i] = x; Y[i] = y;
    }

    Tree tree;

    int lo = 0, hi = C / 4 + 1;
    while (hi - lo > 1) {
    int mid = (hi + lo) / 2;
    vector<P> ps;
    REP (i, N) if (Y[i] - X[i] >= mid && X[i]+C - Y[i] >= mid) {
        ps.emplace_back(X[i], Y[i]);
        ps.emplace_back(Y[i], X[i]+C);
    }

    bool yes = false;
    if (ps.size() <= 1u) {
        yes = false;
    } else {
        node_i = 0;
        tree.build(ps.begin(), ps.end(), 0);
        EACH (e, ps) {
        {
            P low(e->real() + mid, e->imag() + mid);
            P high(e->imag() - mid, e->real() + C - mid);
            if (LEBoth(low, high)) {
            bool tmp = tree.find(low, high, 0, &nodes[0]);
            if (tmp) {
                yes = true;
                break;
            }
            }
        }
        {
            P low(e->imag() + mid, e->imag() + mid);
            P high(e->real() + C - mid, e->real() + C - mid);
            if (LEBoth(low, high)) {
            bool tmp = tree.find(low, high, 0, &nodes[0]);
            if (tmp) {
                yes = true;
                break;
            }
            }
        }
        }
    }

    (yes? lo : hi) = mid;
    }

    printf("%d\n", lo);

    return 0;
}

{"mode":"full","isActive":false}


Post a Comment

0 Comments