• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Wednesday, February 1, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Police Operation – HackerRank Solution

Police Operation - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

admin by admin
August 23, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Police Operation – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ replace HackerRank Solution
  • Java rep HackerRank Solution
  • Python 3 rep HackerRank Solution
  • Python 2 rep HackerRank Solution
  • C rep HackerRank Solution
    • Warmup Implementation Strings Sorting Search Graph Theory Greedy Dynamic Programming Constructive Algorithms Bit Manipulation Recursion Game Theory NP Complete Debugging
    • Leave a comment below
      • Related posts:

Police Operation – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ replace HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>
int n, h, st, ed;
long long inp[2000010], deq[2000010], dp[2000010];
inline long long sq(long long x) {
    return x * x;
}
inline long long calc(long long x1, long long v1, long long x2, long long v2) {
    return (v1 - v2 - x2*x2 + x1*x1 + 2*(x1-x2) - 1) / ( 2*(x1-x2));
}
int main() {
    scanf("%d%d", &n, &h);
    for (int i=1; i<=n; i++) scanf("%lld", &inp[i]);
    st = 0;
    ed = 0;
    deq[st++] = 0;
    for (int i=1; i<=n; i++) {
        while (st > ed + 1 && dp[deq[ed]] + sq(inp[i] - inp[deq[ed]+1]) >=
                              dp[deq[ed+1]] + sq(inp[i] - inp[deq[ed+1]+1])) {
            ed ++;
        }
        dp[i] = dp[deq[ed]] + sq(inp[i] - inp[deq[ed]+1]) + h;
        if (i < n) {
            while (st > ed + 1 && calc(inp[deq[st-1]+1], dp[deq[st-1]], inp[deq[st-2]+1], dp[deq[st-2]]) >=
                                  calc(inp[i+1], dp[i], inp[deq[st-1]+1], dp[deq[st-1]])) {
                st --;
            }
            deq[st++] = i;
        }
    }
    printf("%lld\n", dp[n]);
    return 0;
}

Java rep HackerRank Solution


Copy Code Copied Use a different Browser

 

import java.io.*;
import java.util.*;

public class Solution {

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;
	boolean eof;

	static class Line {
		long k;
		long b; // y = k * x + b

		public Line(long k, long b) {
			this.k = k;
			this.b = b;
		}

		double cross(Line o) {
			return 1.0 * (o.b - b) / (k - o.k);
		}

		long vect(Line a) {
			return k * a.b - a.k * b;
		}
	}

	boolean badTurn(Line a, Line b, Line c) {
		return a.vect(b) + b.vect(c) + c.vect(a) >= 0;
	}

	void solve() throws IOException {
		int n = nextInt();
		int h = nextInt();
		int[] xs = new int[n];
		for (int i = 0; i < n; i++) {
			xs[i] = nextInt();
		}
		if (n == 0) {
			out.println(0);
			return;
		}
		if (n == 1) {
			out.println(h);
			return;
		}
		long[] dp = new long[n + 1];
		Line[] s = new Line[n + 1];
		int sz = 0;
		s[sz++] = new Line(-2 * xs[0], h + sqr(xs[0]));
		double[] c = new double[n + 1];
		for (int i = 0; i < n; i++) {
			int pos = Arrays.binarySearch(c, 0, sz - 1, xs[i]);
			if (pos < 0) {
				pos = -pos - 1;
			}
			dp[i + 1] = Long.MAX_VALUE;
			for (int j = pos - 1; j <= pos + 1; j++) {
				if (j >= 0 && j < sz) {
					dp[i + 1] = Math.min(dp[i + 1], s[j].k * xs[i] + s[j].b);
				}
			}
			dp[i + 1] += sqr(xs[i]);
			if (i != n - 1) {
				Line add = new Line(-2 * xs[i + 1], h + dp[i + 1] + sqr(xs[i + 1]));
//				System.err.println(dp[i + 1] + ", " + add.k + " " + add.b);
				while (sz > 1 && badTurn(s[sz - 2], s[sz - 1], add)) {
					sz--;
				}
				s[sz++] = add;
				c[sz - 2] = s[sz - 2].cross(s[sz - 1]);
			}
		}
		out.println(dp[n]);
	}

	static long sqr(long x) {
		return x * x;
	}

	Solution() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new Solution();
	}

	String nextToken() {
		while (st == null || !st.hasMoreTokens()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				eof = true;
				return null;
			}
		}
		return st.nextToken();
	}

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			eof = true;
			return null;
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
}



Python 3 rep HackerRank Solution


Copy Code Copied Use a different Browser

#!/bin/python3

import os
import sys

#
# Complete the policeOperation function below.
#
def cross(f, g):
    return (g[1]-f[1])/(f[0]-g[0])

def policeOperation(h, criminals):
    n = len(criminals)
    dp = 0
    stack = []
    fpos = 0
    for i in range(0,n):
        f = [-2*criminals[i],criminals[i]*criminals[i] + dp,0]
        
        while len(stack) > 0:
            f[2] = cross(stack[-1], f)
            if stack[-1][2] < f[2]:
                break
            stack.pop()
            if len(stack) == fpos:
                fpos -= 1

        stack.append(f)
        x = criminals[i];
        while fpos+1 < len(stack) and stack[fpos+1][2] < x: fpos += 1
        dp = stack[fpos][0] * x + stack[fpos][1] + h + x*x;   

    return dp




if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nh = input().split()

    n = int(nh[0])

    h = int(nh[1])
    result = 0
    if n != 0:
        criminals = list(map(int, input().rstrip().split()))
        result = policeOperation(h, criminals)

    fptr.write(str(result) + '\n')

    fptr.close()



Python 2 rep HackerRank Solution


Copy Code Copied Use a different Browser

 



C rep HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>
#include <stdlib.h>
int get_i(double *a,int num,int size);
double med(double *a,int size);
double inter(long long m1,long long n1,long long m2,long long n2);
int a[2000000];
long long dp[2000000],m[2000000],n[2000000];
double aa[2000000];

int main(){
  int N,h,aa_size=0,i,j;
  long long t,tt;
  scanf("%d%d",&N,&h);
  for(i=0;i<N;i++)
    scanf("%d",a+i);
  for(i=0;i<N;i++){
    if(i)
      dp[i]=h+dp[i-1];
    else
      dp[i]=h;
    if(i && a[i]==a[i-1]){
      dp[i]=dp[i-1];
      continue;
    }
    if(aa_size){
      j=get_i(aa,a[i],aa_size-1);
      t=a[i]*(long long)a[i]+m[j]*a[i]+n[j];
      if(t<dp[i])
        dp[i]=t;
    }
    m[aa_size]=-2*a[i];
    if(i)
      n[aa_size]=a[i]*(long long)a[i]+h+dp[i-1];
    else
      n[aa_size]=a[i]*(long long)a[i]+h;
    j=++aa_size;
    while(aa_size>2){
      if(inter(m[aa_size-3],n[aa_size-3],m[j-1],n[j-1])>aa[aa_size-3])
        break;
      aa_size--;
    }
    tt=m[j-1];
    m[j-1]=m[aa_size-1];
    m[aa_size-1]=tt;
    tt=n[j-1];
    n[j-1]=n[aa_size-1];
    n[aa_size-1]=tt;
    if(aa_size>1)
      aa[aa_size-2]=inter(m[aa_size-2],n[aa_size-2],m[aa_size-1],n[aa_size-1]);
  }
  printf("%lld",dp[N-1]);
  return 0;
}
int get_i(double *a,int num,int size){
  if(size==0)
    return 0;
  if(num>med(a,size))
    return get_i(&a[(size+1)>>1],num,size>>1)+((size+1)>>1);
  else
    return get_i(a,num,(size-1)>>1);
}
double med(double *a,int size){
  return a[(size-1)>>1];
}
double inter(long long m1,long long n1,long long m2,long long n2){
  return (n2-n1)/(double)(m1-m2);
}

 

Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionBike Racers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTime Conversion – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionNo Prefix Set – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionHuarongdao – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree: Huffman Decoding – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptPolice Operationpypy 3Python 2python 3
ShareTweetPin
admin

admin

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
30

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Zurikela's Graph- HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Modify The Sequence- HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionBike Racers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTime Conversion – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionNo Prefix Set – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionHuarongdao – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree: Huffman Decoding – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Omniscient Reader's Viewpoint
Anime

Omniscient Reader’s Viewpoint Chapter 123: Raw Scan English Spoilers

September 7, 2022
13
Biography

Jason Paul Behrendorff Net Worth, Age, Height , Achivements and more

September 22, 2022
3
Leetcode All Problems Solutions
Code Solutions

Can Place Flowers – LeetCode Solution

September 11, 2022
28
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Mini-Max Sum – HackerRank Solution

May 31, 2022
14

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?