• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Saturday, February 4, 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

Animal Transport – HackerRank Solution

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

bhautik bhalala by bhautik bhalala
May 31, 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

  • Animal Transport – 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++ Animal Transport HackerRank Solution
  • Java Animal Transport 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:

Animal Transport – 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++ Animal Transport HackerRank Solution


Copy Code Copied Use a different Browser

#include <bits/stdc++.h>
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define lp(i,a,n) for(int i=a;i<=n;++i)
#define lpd(i,a,n) for(int i=a;i>=n;--i)
#define mem(a,b) memset(a,b,sizeof a)
#define all(v) v.begin(),v.end()
#define println(a) cout <<(a) <<endl
#define sz(x) ((int)(x).size())
#define readi(x) scanf("%d",&x)
#define read2i(x,y) scanf("%d%d",&x,&y)
#define read3i(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define mod 1000000007
#define eps 1e-8
#define infi 1000000000
#define infll 1000000000000000000ll
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef set<int> si;
typedef map<int,int> mii;

const int N = 50002;
int t,m,n,dp[N][2];
int tree[4*N][2],lazy[4*N][2];
int type[N],s[N],d[N];
vvi g(N);

void propagate(int i, int j, bool leaf){
    tree[i][j] += lazy[i][j];
    if(!leaf){
        lazy[2*i][j] += lazy[i][j];
        lazy[2*i+1][j] += lazy[i][j];
    }
    lazy[i][j] = 0;
}

int query(int i, int start, int end, int l, int r, int j){
    propagate(i, j, start == end);
    if(l <= start && r >= end) return tree[i][j];
    if(r < start || l > end) return 0;
    int mid = (start+end)/2;
    return max(query(2*i,start,mid,l,r,j), query(2*i+1,mid+1,end,l,r,j));
}

void update(int i, int start, int end, int l, int r, int j, int v){
    propagate(i, j, start == end);
    if(l <= start && r >= end){
        lazy[i][j] += v;
        propagate(i, j, start == end);
        return;
    }
    if(r < start || l > end) return;

    int mid = (start+end)/2;
    update(2*i, start, mid, l, r, j, v);
    update(2*i+1, mid+1, end, l, r, j, v);

    tree[i][j] = max(tree[2*i][j], tree[2*i+1][j]);
}

int main(){
    readi(t);
    while(t--){
        read2i(m,n);
        lp(i,1,n){
            char c;
            scanf(" %c", &c);
            type[i] = c == 'D' or c == 'M' ? 0 : 1;
        }
        lp(i,1,n) readi(s[i]);
        lp(i,1,n) readi(d[i]), g[d[i]].pb(i);

        lp(i,1,m){
            for(int idx : g[i]) if(s[idx] < i) update(1,1,m, 1, s[idx], !type[idx], 1);
            dp[i][0] = query(1,1,m, 1, i, 1);
            dp[i][1] = query(1,1,m, 1, i, 0);
            update(1,1,m, i, i, 0, dp[i][0]);
            update(1,1,m, i, i, 1, dp[i][1]);
        }

        vi ans;
        lp(i,1,m) ans.pb(max(dp[i][0], dp[i][1]));
        lp(i,1,n){
            int x = lower_bound(all(ans), i) - ans.begin() + 1;
            if(x == m+1) x = -1;
            printf("%d ", x);
        }
        puts("");

        g.clear();
        g.resize(N);
        mem(tree, 0);
        mem(lazy, 0);
    }
}

/*
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
*/

Java Animal Transport HackerRank Solution


Copy Code Copied Use a different Browser

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int[] minimumZooNumbers(int m, int n, List<Boolean>[] type, List<Integer>[] start) {
        SegRangeAddMax seg0 = new SegRangeAddMax(m);
        SegRangeAddMax seg1 = new SegRangeAddMax(m);
        
        int[] res0 = new int[m];
        
        //supposed to be that si != di
        for(int i=1; i<m; i++){
            List<Boolean> ty = type[i];
            List<Integer> st = start[i];
            
            for(int j=0; j<st.size(); j++){
                boolean t = ty.get(j);
                int s = st.get(j);
                SegRangeAddMax affected = t ? seg1 : seg0;
                affected.modify(0, s, 1);
            }
            int qmax = Math.max(seg0.query(0, i-1), seg1.query(0, i-1));
            seg0.modify(i, i, qmax);
            seg1.modify(i, i, qmax);
            res0[i] = qmax;
        }
        
        //System.out.println(Arrays.toString(res0));
        
        int[] res = new int[n];
        for(int i=0; i<n; i++){
            res[i] = -1;
        }
        
        for(int i=m-1; i>=1; i--){
            if(res0[i] - 1 >= 0) res[res0[i]-1] = i+1;
        }
        int prev = -1;
        for(int i=n-1; i>=0; i--){
            if(res[i] == -1) res[i] = prev;
            prev = res[i];
        }
        
        //System.out.println(Arrays.toString(res));
        return res;
        
        //List<Integer> 
        // Return a list of length n consisting of the answers
        //return new int[1];
    }

    public static void main(String[] args) {
        FasterScanner in = new FasterScanner(System.in);
        int cases = in.nextInt();
        for(int a0 = 0; a0 < cases; a0++){
            int m = in.nextInt();
            int n = in.nextInt();
            
            List<Boolean>[] type = new ArrayList[m];
            List<Integer>[] start = new ArrayList[m];
            
            
            //stupid one-indexed elements -_-
            for(int i=0; i<m; i++){
                type[i] = new ArrayList<Boolean>();
                start[i] = new ArrayList<Integer>();
            }
            
            
            
            for(int i=0; i<n; i++){}
            
            //boolean[] t = new boolean[n];
            char[] t = new char[n];
            for(int t_i = 0; t_i < n; t_i++){
                //char c = in.next().charAt(0);
                //t[t_i] = c == 'D' || c == 'M';
                t[t_i] = in.next().charAt(0);
            }
            
            
            int[] s = new int[n];
            for(int s_i = 0; s_i < n; s_i++){
                s[s_i] = in.nextInt()-1;
            }
            
            
            
            int[] d = new int[n];
            for(int d_i = 0; d_i < n; d_i++){
                d[d_i] = in.nextInt()-1;
                //if(s[d_i] >= d[d_i]) throw new RuntimeException();
                //^ sanity check. Huge troll if they decide to put this in.
                //^ though I will say that I can cope w/ it quite easily in case they do troll.
                //^ just don't push to your lists when this condition fails
                //^ todo later: implement that since dunno if full test suite runs later.
            }
            
            for(int i=0; i<n; i++){
                if(s[i] >= d[i]) continue;
                type[d[i]].add(t[i] == 'D' || t[i] == 'M');
                start[d[i]].add(s[i]);
            }
            
            
            int[] result = minimumZooNumbers(m, n, type, start);
            for (int i = 0; i < result.length; i++) {
                System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
            }
            System.out.println("");


        }
        
        
        //int[] testA = new int[]{1, 3, 5, 4, 0};
        //SegRangeAddMax test = new SegRangeAddMax(testA);
        //System.out.println(test.query(3,3));
        
    }
}

//DUNNO IF THIS WORKS YET. gonna test on hr: animal transport

class SegRangeAddMax{
	int[] t, d;
	int n, h;

	SegRangeAddMax(int[] base){
		this(base.length);
		for(int i=0; i<n; i++)
			t[i+n] = base[i];
		for(int i=n-1; i>0; i--)
			t[i] = t[i<<1] + t[i<<1|1];
	}

	SegRangeAddMax(int n){
		this.n = n;
		h = 32 - Integer.numberOfLeadingZeros(n);
        t = new int[2*n];
        d = new int[n];
	}

	//k is the width of the interval denoted by p
	void apply(int p, int val){
		t[p] += val;
		if(p < n) d[p] += val;
	}

	void calc(int p){
		t[p] = Math.max(t[p<<1],t[p<<1|1]) + d[p];
	}

	//before and after the build() function is called,
	//invariant that t[p] == t[p] of both children + d[p]*k, holds. < ignore this.
	void build(int p){
		//int k = 2;
		for(p+=n; p>1;){
			p >>= 1;
			calc(p);
		}
	}

	//its obvious that invariant t[p] == t[p] of both children + d[p]*k holds during a push. < ignore this.
	void push(int p){
		//int k = 1 << (h-1);
		int s = h;
		for(p+=n; s>0; s--){
			int i = p >> s;
			if(d[i] != 0){
				apply(i<<1, d[i]);
				apply(i<<1|1, d[i]);
				d[i] = 0;
			}
		}
	}

	void modify(int l, int r, int val){
		r++;
		if(val == 0) return;
		//push(l);
		//push(r-1);
		int l0=l, r0=r;
		for(l+=n, r+=n; l<r; l >>= 1, r >>= 1){
			if((l&1) == 1) apply(l++, val);
			if((r&1) == 1) apply(--r, val);
		}
		build(l0);
		build(r0-1);
	}

	int query(int l, int r){
		r++;
		push(l);
		push(r-1);
		int res = Integer.MIN_VALUE;
		for(l+=n, r+=n; l<r; l >>= 1, r >>= 1){
			if((l&1) == 1) res = Math.max(res, t[l++]);
    		if((r&1) == 1) res = Math.max(res, t[--r]);
		}
		return res;
	}
}

class FasterScanner {
	private InputStream mIs;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;

	public FasterScanner() {
		this(System.in);
	}

	public FasterScanner(InputStream is) {
		mIs = is;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = mIs.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	//nextString
	public String next() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

 



 

 

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)-SolutionTwo Strings Game – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSorted Subsegments – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionQueue using Two Stacks – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionReal Estate Broker – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree Flow – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionBeautiful 3 Set – HackerRank Solution
Tags: Animal TransportCc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

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
27
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
53
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

Requirement - HackerRank Solution

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

A Super Hero - 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)-SolutionTwo Strings Game – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSorted Subsegments – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionQueue using Two Stacks – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionReal Estate Broker – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree Flow – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionBeautiful 3 Set – 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
Jujutsu Kaisen Chapter 183 Spoilers Reddit , Release Date , Raws
Anime

Jujutsu Kaisen Chapter 183 Spoilers Reddit , Release Date , Raws

May 5, 2022
43
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Diameter Minimization – HackerRank Solution

May 27, 2022
10
Biography

Karishma Kapoor Net Worth, Age, Height , Achivements and more

September 8, 2022
0
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Time Conversion – HackerRank Solution

May 31, 2022
6

© 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?