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

Liars – HackerRank Solution

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

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

  • Liars – 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++ Liars HackerRank Solution
  • Java Liars HackerRank Solution
  • Python 3 rep HackerRank Solution
  • Python 2 Liars HackerRank Solution
  • C Liars HackerRank Solution
    • Leave a comment below
      • Related posts:

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


Copy Code Copied Use a different Browser

#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

const int MAXN = 150;

typedef pair<int, int> P;

int d[MAXN];
vector<P> e[MAXN];
int a[MAXN], b[MAXN], c[MAXN];

deque<int> dq;
int inq[MAXN];

int n, m;

int getMin() {
  for (int i = 0; i <= n; ++i) e[i].clear();
  for (int i = 1; i <= n; ++i) {
    e[i - 1].push_back(P(i, 0));
    e[i].push_back(P(i - 1, -1));
  }
  for (int i = 0; i < m; ++i) {
    e[b[i]].push_back(P(a[i] - 1, -c[i]));
    e[a[i] - 1].push_back(P(b[i], c[i]));
  }
  fill(d, d + (n + 1), 0);
  d[0] = 0;

  for (int c = 0; c <= n; ++c) 
    for (int u = 0; u <= n; ++u)
      for (int j = 0; j < e[u].size(); ++j) {
	int v = e[u][j].first;
	if (d[u] + e[u][j].second > d[v]) d[v] = d[u] + e[u][j].second;
      }
  return d[n];

  fill(inq, inq + (n + 1), 0);
  inq[0] = 1;
  while (!dq.empty()) dq.pop_back();
  dq.push_back(0);
  while (!dq.empty()) {
    int u = dq.front();
    dq.pop_front();
    inq[u] = 0;
    for (int j = 0; j < e[u].size(); ++j) {
      int v = e[u][j].first;
      if (d[u] + e[u][j].second > d[v]) {
	d[v] = d[u] + e[u][j].second;
	if (!inq[v]) {
	  inq[v] = 1;
	  dq.push_back(v);
	}
      }
    }
  }
  return d[n];
}

int getMax() {
  for (int i = 0; i <= n; ++i) e[i].clear();
  for (int i = 1; i <= n; ++i) {
    e[i].push_back(P(i - 1, 0));
    e[i - 1].push_back(P(i, 1));
  }
  for (int i = 0; i < m; ++i) {
    e[b[i]].push_back(P(a[i] - 1, -c[i]));
    e[a[i] - 1].push_back(P(b[i], c[i]));
  }
  fill(d, d + (n + 1), n * 2);
  d[0] = 0;

  for (int c = 0; c <= n; ++c) 
    for (int u = 0; u <= n; ++u)
      for (int j = 0; j < e[u].size(); ++j) {
	int v = e[u][j].first;
	if (d[u] + e[u][j].second < d[v]) d[v] = d[u] + e[u][j].second;
      }
  return d[n];

  fill(inq, inq + (n + 1), 0);
  inq[0] = 1;
  while (!dq.empty()) dq.pop_back();
  dq.push_back(0);
  while (!dq.empty()) {
    int u = dq.front();
    dq.pop_front();
    inq[u] = 0;
    for (int j = 0; j < e[u].size(); ++j) {
      int v = e[u][j].first;
      if (d[u] + e[u][j].second < d[v]) {
	d[v] = d[u] + e[u][j].second;
	if (!inq[v]) {
	  inq[v] = 1;
	  dq.push_back(v);
	}
      }
    }
  }
  return d[n];
}

int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; ++i) {
    scanf("%d%d%d", a + i, b + i, c + i);
  }

  printf("%d %d\n", getMin(), getMax());
}

Java Liars HackerRank Solution


Copy Code Copied Use a different Browser

import java.util.*;
import java.io.*;
import static java.lang.Math.*;

public class Solution {
	/*
	 * difference constraints
	 * add new constraint d[N]-d[0] = k and check if k is feasible
	 */
	static class Foo51 {
		int N;
		int[][] edges;
		void main() {
			BufferedReader br = null;
			try {
				br = new BufferedReader(new InputStreamReader(System.in));
				String[] s = br.readLine().trim().split(" ");
				N = Integer.parseInt(s[0].trim());
				int M = Integer.parseInt(s[1].trim());
				edges = new int[2*M+2*N+2][3];
				for (int i = 0; i < M; i++) {
					s = br.readLine().trim().split(" ");
					int u = Integer.parseInt(s[0].trim());
					int v = Integer.parseInt(s[1].trim());
					int weight = Integer.parseInt(s[2].trim());
					edges[2*i] = new int[] {u-1, v, weight};
					edges[2*i+1] = new int[] {v, u-1, -weight};
				}
				for (int i = 0; i < N; i++) {
					edges[2*i+2*M] = new int[] {i+1, i, 0};
					edges[2*i+2*M+1] = new int[] {i, i+1, 1};
				}
				edges[2*M+2*N][0] = edges[2*M+2*N+1][1] = 0;
				edges[2*M+2*N+1][0] = edges[2*M+2*N][1] = N;
				int[] res = foo();
				System.out.println(res[0] + " " + res[1]);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (br != null) {
					try { br.close(); } catch (Exception e) { e.printStackTrace(); }
				}
			}
		}
		int[] foo() {
			// binary search is better, but since the constraint is low, just linear traverse
			int[] res = {N, 0};
			for (int k = 0; k <= N; k++) {
				if (ok(k)) {
					res[0] = min(res[0], k);
					res[1] = max(res[1], k);
				}
			}
			return res;
		}
		boolean ok(int K) {
			int m = edges.length;
			edges[m-2][2] = K;
			edges[m-1][2] = -K;
			int[] d = new int[N+1];
			for (int i = 0; i < N+1; i++) {
				for (int j = 0; j < m; j++) {
					int u = edges[j][0];
					int v = edges[j][1];
					d[v] = min(d[v], d[u]+edges[j][2]);
				}
			}
			for (int j = 0; j < m; j++) {
				int u = edges[j][0];
				int v = edges[j][1];
				if (d[v] > d[u] + edges[j][2])
					return false;
			}
			return true;
		}
	}
	
	public static void main(String[] args) {
		Foo51 foo = new Foo51();
		foo.main();
	}
}

 



Python 3 rep HackerRank Solution


Copy Code Copied Use a different Browser

from sys import stdin
from math import inf
from queue import Queue

def find_liars(num_soldiers, source_soldier, dest_soldier, edges):
  liars = [inf] * (num_soldiers + 1)
  liars[source_soldier] = 0

  for fodder in range(0, num_soldiers + 1):
      for edge in edges:
        soldier, next_soldier, liar_count = edge
        calc_liars = liar_count + liars[soldier]
        if calc_liars < liars[next_soldier]:
          liars[next_soldier] = calc_liars

  return liars[dest_soldier]

def run():
  soldiers, num_info = [int(info) for info in input().strip().split(' ')]
  edges = [[(i, i+1, 1)] for i in range(0, soldiers)]
  edges.append([])
  for i in range(0, soldiers):
    edges[i + 1].append((i+1, i, 0))

  # read information input
  for line in stdin:
    first_soldier, second_soldier, liars = [int(info) for info in line.strip().split(' ')]
    edges[first_soldier - 1].append((first_soldier - 1, second_soldier, liars))
    edges[second_soldier].append((second_soldier, first_soldier - 1, -liars))

  edges = [edge for edge_soldiers in edges for edge in edge_soldiers ]

  max_liars = find_liars(soldiers, 0, soldiers, edges)
  min_liars = -find_liars(soldiers, soldiers, 0, edges)
  
  print(min_liars, max_liars)

run()



Python 2 Liars HackerRank Solution


Copy Code Copied Use a different Browser

#Write your Python code here. Input is from STDIN and output to STDOUT. Please refer FAQ for more details.\
#!/usr/bin/python

def get(n, limit):
    edges = []
    virtual = n+1
    for x in xrange(n):
        edges.append((x+1, x, 0))
        edges.append((x, x+1, 1))
    for x in xrange(n+1):
        edges.append((virtual, x, 0))
    for a, b, c in limit:
        edges.append((a-1, b, c))
        edges.append((b, a-1, -c))

    dist = [10**10] * (n+2)
    dist[virtual] = 0
    for x in xrange(n+1):
        for a, b, c in edges:
            dist[b] = min(dist[b], dist[a] + c)
    return dist[n] - dist[0]


getnums = lambda: map(int, raw_input().strip().split())
n, m = getnums()
limit = []
reverse = []
for x in xrange(m):
    a, b, c = getnums()
    limit.append((a, b, c))
    reverse.append((a, b, b-a+1-c))
print get(n, limit), n-get(n, reverse)



C Liars HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>

#define N 500
#define eps 0.00000000000001

long long MM,NN,baza[500],i,j,k,l,m,n,interval[N][3],je_v_bazi[N];
long double a[N][N],b[N],c[N],r,s,t,z;


void pivotuj(long long mm,long long nn, long long kk, long long ii)
{
long long jj,ll;
long double rr;

baza[kk] = ii;

rr= a[kk][ii];

for(jj=0;jj<nn;jj++) a[kk][jj] /= rr;
b[kk]/=rr;


for(ll=0;ll<mm;ll++)
{
 if(ll==kk) continue;
 rr = -a[ll][ii];
 
 if(rr<eps && rr>-eps) continue;
 
 b[ll] += b[kk]*rr;
 
 for(jj=0;jj<nn;jj++) 
   a[ll][jj] += a[kk][jj]*rr;
} 
 
 rr = -c[ii];
//printf("%lld %lld %lld %lld %llf\n",mm,nn,kk,ii,rr);
 for(jj=0;jj<nn;jj++) c[jj] += rr*a[kk][jj];

  z -= rr*b[kk];
//printf("%llf..\n",z);
 
return;
}

void vypis(long long mm, long long nn)
{
long long ii,jj;

return;

for(ii=0;ii<mm;ii++)
 {
 for(jj=0;jj<nn;jj++) printf("%5.2llf ",a[ii][jj]);
 printf("| %llf baza %lld\n",b[ii],baza[ii]);
 }

printf("---------------------\n");
for(jj=0;jj<nn;jj++) printf("%5.2llf ",c[jj]);
printf("%llf=z\n\n\n",z);

return; 
}

long long simplex(long long mm, long long nn)
{
long long ii,jj,p_riadok, p_stlpec;
long double rr;

rr=1;
for(ii=0;ii<nn;ii++) 
  if(c[ii]<rr) {rr = c[ii]; p_stlpec=ii;}

if(rr>-eps) 
  {
//  printf("koncim!!\n");
  return 0;
  }

p_riadok = -1;
rr = -1;
for(jj=0;jj<mm;jj++)
 if(a[jj][p_stlpec]>eps)
  if(rr<0 || b[jj]/a[jj][p_stlpec] < rr) {rr = b[jj]/a[jj][p_stlpec];p_riadok = jj;}

if(rr<-eps) 
 {
// printf("neobmedznee!!\n");
 return 0;
 }

//printf("%lld %lld - pivotujem\n",p_riadok, p_stlpec);

pivotuj(mm,nn,p_riadok,p_stlpec);

vypis(mm,nn);

return 1;
}

int main()
{

scanf("%lld %lld",&n,&m);
for(i=0;i<m;i++) 
  {
    scanf("%lld %lld %lld",&interval[i][0],&interval[i][1],&interval[i][2]);
    interval[i][0]--;
    interval[i][1]--;
  }

for(i=0;i<m;i++)
 for(j=interval[i][0];j<=interval[i][1];j++)
             a[i][j] = 1;

for(i=m;i<m+n;i++)
  a[i][i-m] = 1;

for(i=0;i<n+m;i++) a[i][i+n]=1;

for(i=0;i<m;i++) b[i] = interval[i][2];
for(i=m;i<m+n;i++) b[i] = 1;

for(i=n;i<n+m;i++) c[i]=1;
//for(i=0;i<n+m;i++) baza[i] = i+n;

z=0;

vypis(m+n,2*n+m);

for(i=0;i<m+n;i++)
pivotuj(m+n,2*n+m,i,i+n);
//nuluj_b(m+n,2*n+m);

vypis(m+n,2*n+m);


while(simplex(m+n,2*n+m));

//simplex(m+n,2*n+m);

//if(z>eps || z<-eps) {printf("nema ries\n");return 0;}

//return 0;


//for(i=0;i<m+n;i++) if(baza[i]<n) printf("%lld %llf\n", baza[i],b[i]);


//for(i=0;i<2*n+m;i++) neni[i]=1;
//for(i=0;i<m+n;i++) neni[baza[i]]=0;

vypis(m+n,2*n+m);

for(i=0;i<m+n;i++) 
  if(baza[i]>=n && baza[i]<n+m) 
   {
//   printf("..%lld %llf\n", baza[i],b[i]);
   
   j=0;
   while(j<2*n+m && ((j>=n && j<m+n) || (a[i][j]<eps && a[i][j]>-eps)))
     j++; 
   
   if(j>=2*n+m) {
                 //printf("bug!!\n");
                 continue;}
  
//  printf("piv %lld %lld %lld\n",i,j,baza[i]);
   
   pivotuj(m+n,m+2*n,i,j);   
   }

//vypis(n+m,2*n+m);
//return 0;


l=0;
for(i=0;i<m+n;i++) 
  if(baza[i]>=n && baza[i]<n+m) 
   {
   l++;
//   printf("......%lld %llf\n", baza[i],b[i]);
   }

for(i=0;i<m+2*n;i++) je_v_bazi[i]=0;
for(i=0;i<m+n;i++) je_v_bazi[baza[i]]=1;


MM = m+n;
NN = n;

for(i=n;i<2*n+m;i++)
 if(je_v_bazi[i] || i> n+m)
 {
 for(k=0;k<m+n;k++) a[k][NN] = a[k][i];
 c[NN] = c[i];
 
 for(k=0;k<m+n;k++) if(baza[k]==i) baza[k] = NN;
 
 NN++;
 }

z = 0.0;
for(i=0;i<n;i++) c[i] = 1.0;
for(i=n;i<NN;i++) c[i] = 0.0;

//printf("druha faza\n");

//vypis(MM,NN);

//return 0;

//return 0;

for(i=0;i<MM;i++) 
 pivotuj(MM,NN,i,baza[i]);

vypis(MM,NN);

//return 0;

while(simplex(MM,NN));

vypis(MM,NN);


printf("%lld", (long long)(z+0.5));

//return 0;

z = 0;
for(i=0;i<n;i++) c[i] = -1;
for(i=n;i<NN;i++) c[i] = 0;

//printf("druha faza\n");

for(i=0;i<MM;i++) pivotuj(MM,NN,i,baza[i]);

vypis(MM,NN);

while(simplex(MM,NN));

printf(" %lld\n", (long long)(-z+0.5));


 return 0;
}

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionMaking Candies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDiagonal Difference – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionJesse and Cookies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionToll Cost Digits – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionByteLandian Tours – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptLiarspypy 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

Jumping Rooks - HackerRank Solution

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

Frog in Maze - 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)-SolutionMaking Candies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDiagonal Difference – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionJesse and Cookies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionToll Cost Digits – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionByteLandian Tours – 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
Leetcode All Problems Solutions
Code Solutions

N-Queens – LeetCode Solution

September 3, 2022
147
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Decibinary Numbers – HackerRank Solution

May 27, 2022
25
Biography

Alex Tyson Carey Net Worth, Age, Height , Achivements and more

September 22, 2022
6
Leetcode All Problems Solutions
Code Solutions

Best Time to Buy and Sell Stock III – LeetCode Solution

September 5, 2022
63

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