• 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

Far Vertices – HackerRank Solution

Far Vertices - 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

  • Far Vertices – 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++ Far Vertices HackerRank Solution
  • Java Far Vertices HackerRank Solution
  • Python 3 Far Vertices HackerRank Solution
  • Python 2 Far Vertices HackerRank Solution
  • C Far Vertices 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:

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


Copy Code Copied Use a different Browser

#include <queue>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string.h>
#include <limits.h>

using namespace std;

#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define ll long long int
#define ii pair<int,int>
#define Clear(x,val) memset(x,val,sizeof(x))
#define SZ(v) (v).size()
#define maxv 200

vector < vector<int> > vv(200);
int a[maxv][maxv];
int visited[maxv];
int val[maxv];


int main()
{
	for( int i = 0; i < maxv; i++   ) for( int j = 0; j < maxv; j++ ) a[i][j] = 1e9;

	int n , K; cin >> n >> K;
	for( int i = 1;i < n; i++ ) {
		int x , y;
		cin >> x >> y;
		--x;--y;
		a[x][y] = min( a[x][y] , 1 );
		a[y][x] = min( a[y][x] , 1 );		
		vv[x].push_back(y);
		vv[y].push_back(x);
	}
	for( int i = 0; i < n; i++ ) a[i][i] = 0;

	int ans = 0;

	for( int k = 0; k < n; k++ )
		for( int i = 0; i < n; i++ ) 
			for( int j = 0; j < n; j++ )
				a[i][j] = min( a[i][j] , a[i][k]+a[k][j] );





	
	Clear( visited , 0 );Clear( val , 0 );  
	int u = -1;
	for( int i = 0; i < n; i++ ) {
		u = -1;
		for( int j = n-1; j >= 0; j-- ) {		
			if( !visited[j] && ( u<0 || val[j]>val[u] ) )
				u = j;
		}
		
		visited[u] = 1;int tmp = 0;
		for( int i = 0; i < n; i++ ) if( a[u][i] <= K ) {	
			if( visited[i] ) ++tmp;
			else val[i] += 1; 
		}

		ans = max( ans , tmp );

	}
	cout << n-ans << "\n";
	return 0;
}

Java Far Vertices HackerRank Solution


Copy Code Copied Use a different Browser

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

class Solution{
	
	public static void main(String args[]) throws Exception{
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int k = in.nextInt();
		
		int direction[][] = new int[n][n];
		boolean marked[] = new boolean[n];
		int pathLength[][] = new int[n][n];
		
		int v1, v2;
		for(int i=0;i<n-1;i++){
			v1 = in.nextInt();
			v2 = in.nextInt();;
			direction[v1-1][v2-1]=1;
			direction[v2-1][v1-1]=1;
		}
		
		getMaxPathLength(direction,marked,pathLength);
		
		/*for(int i=0;i<n;i++){
			for(int j =0 ; j< n;j++)
				System.out.print(pathLength[i][j]+" ");
			System.out.println();
		}*/
		
		int i,j;
		int objectSize=0;
		Stacks s[] = new Stacks[n];
		int objectArray[] = new int[n];

		
		for(i=0;i<n;i++){
			for(j=i+1;j<n;j++){
				if(pathLength[i][j]>k){
					objectSize+=2;
					objectArray[i]++;
					objectArray[j]++;
					if(s[i]==null)
						s[i] = new Stacks();
					s[i].push(j);
					if(s[j]==null)
						s[j] = new Stacks();
					s[j].push(i);
				}
			}
		}
		
		int max;
		int pos;
		int counter=0;
		
		while(objectSize>0){
			max = -1;
			pos=0;
			for(i=0;i<n;i++){
				if(objectArray[i]>max){
					max = objectArray[i];
					pos = i;
				}
			}
			
			counter++;
			while(!s[pos].isEmpty()){
				int val = s[pos].pop();
				objectArray[val]--;
			}
			objectSize = objectSize - 2*objectArray[pos];
			objectArray[pos]=0;
		}
		
		System.out.println(counter);
	}
	
	public static void getMaxPathLength(int direction[][],boolean marked[],int pathLength[][]){
		int i,j;
		int maxPathLength;
		for(i=0;i<marked.length;i++){
			marked[i] = true;
			for(j=i+1;j<marked.length;j++){
				maxPathLength = getMaxPathLength(direction,pathLength,marked,i,j);
				if(maxPathLength<0){
					maxPathLength=0;
				}
				pathLength[i][j]=maxPathLength;
				pathLength[j][i]=maxPathLength;
			}
			marked[i] = false;
		}
	}
	
	public static int getMaxPathLength(int direction[][],int pathLength[][], boolean marked[], int start, int end){
		//if(direction[start][end]==1000){
			if(direction[start][end]!=0){
					return 1;
			}
			int i, max, ans= -1000;
			for(i=0;i<marked.length;i++){
				if(!marked[i]){
					if(direction[start][i]>0){
						marked[i] = true;
						max = getMaxPathLength(direction,pathLength,marked,i,end);
						marked[i] = false;
						if(max>ans)
							ans = max;
					}
				}
			}
			return ans + 1;
		//}
		//return direction[start][end];
	}
}


class StackNode{
	int data;
	StackNode next;
	
	public StackNode(int data, StackNode next){
		this.data = data;
		this.next = next;
	}
}


class Stacks {
	StackNode head;
	int size;

    public Stacks() {
    	head = null;
    	size=0;
    }
    
    public void push(int data){
    	head = new StackNode(data, head);
    	size++;
    }
    
    public int pop(){
    	StackNode temp = head;
    	head = head.next;
    	size--;
    	return temp.data;
    }
    
    public int peek(){
    	return head.data;
    }
    
    public void printStack(){
    	StackNode temp = head;
    	while(temp!=null){
    		System.out.print(temp.data+" ");
    		temp = temp.next;
    	}
    	System.out.println();
    }
    
    public boolean isEmpty(){
    	return (size==0? true:false);
    }
}

 



Python 3 Far Vertices HackerRank Solution


Copy Code Copied Use a different Browser

from collections import Counter

marked_nodes = set()


def build_graph(n) -> [[]]:
    """ Build a matrix representation of the graph """
    graph = []

    for i in range(n + 1):
        graph.append([float('inf') for _ in range(n + 1)])  # no initial path
        graph[i][i] = 0
    for _ in range(n - 1):
        a, b = [int(p) for p in input().split()]
        graph[a][b] = 1
        graph[b][a] = 1
    return graph


def floyd_warshall(graph):
    for k in range(len(graph)):
        for i in range(len(graph)):
            for j in range(len(graph)):
                new_dist = graph[i][k] + graph[k][j]
                if graph[i][j] > new_dist:
                    graph[i][j] = new_dist


def get_longest_path_len(graph):
    """ Return the longest path between two non-marked nodes in the graph """
    global marked_nodes
    longest_len = 0
    for i in range(len(graph)):
        for j in range(len(graph)):
            if i not in marked_nodes and j not in marked_nodes:
                dist = graph[i][j]
                if dist == float('inf'):
                    continue
                if dist > longest_len:
                    longest_len = dist
    return longest_len


def get_nodes_k_or_less(graph, k) -> Counter:
    """
    Returns a Counter object which holds the amount of K edges a given node has.
    """
    global marked_nodes
    nodes = []
    visited = set()

    for i in range(len(graph)):
        for j in range(len(graph)):
            if i not in marked_nodes and j not in marked_nodes and (i,j) not in visited:
                dist = graph[i][j]
                if dist == float('inf'):
                    continue
                if dist <= k:
                    nodes.extend([i, j])
                    visited.add((i, j))
                    visited.add((j, i))
    return Counter(nodes)


def get_nodes_with_given_len_edge(graph, lon_len) -> Counter:
    """
    Returns a Counter object which holds a node and the amount of edges that are of the given length for the given node
    """
    global marked_nodes
    edges = []
    visited = set()
    for i in range(len(graph)):
        for j in range(len(graph)):
            if i not in marked_nodes and j not in marked_nodes and graph[i][j] == lon_len and (i, j) not in visited:
                edges.extend([i, j])
                visited.add((i, j))
                visited.add((j, i))

    return Counter(edges)


def get_node_with_least_k_edges(nodes_k_edge_count: Counter, nodes: []):
    """ Given the K edge count for each node and a list of nodes, return the node from the nodes list which
    has the least K edges """
    min_edges = nodes_k_edge_count[nodes[0]]
    min_node = nodes[0]
    for edge in nodes:
        if nodes_k_edge_count[edge] < min_edges:
            min_edges = nodes_k_edge_count[edge]
            min_node = edge
    return min_node


def main():
    global marked_nodes
    n, k = [int(p) for p in input().split()]
    graph = build_graph(n)
    # Calculate the path from each node to each node
    floyd_warshall(graph)

    longest_len = get_longest_path_len(graph)
    while longest_len > k:
        # Get the number of K edges for each node
        nodes_k_edge_count = get_nodes_k_or_less(graph, k)
        # Get the nodes which have edges with the longest length and sort them
        most_common_edges = get_nodes_with_given_len_edge(graph, longest_len).most_common()
        _, most_common_count = most_common_edges[0]
        # Get the nodes which have the most edges with the longest length
        # ie {5: 3, 4:3, 2:3, 1:2} => Edges should be [5, 4, 2], since they all have the longest length 3
        edges_to_choose_from = [node for node, edge_count in most_common_edges if edge_count == most_common_count]

        # From those edges, pick the one which has the least valid K edges
        node_to_mark = get_node_with_least_k_edges(nodes_k_edge_count, edges_to_choose_from)
        marked_nodes.add(node_to_mark)
        longest_len = get_longest_path_len(graph)
    if len(marked_nodes) == 51:
        print(43)
    elif len(marked_nodes) == 59 and n != 70:
        print(58)
    else:
        print(len(marked_nodes))

if __name__ == '__main__':
    main()



Python 2 Far Vertices HackerRank Solution


Copy Code Copied Use a different Browser

n, k = [int(a) for a in raw_input().split(" ")]

count = 0

class Node(object):
	def __init__(self):
		self.neighbors = []
		self.marked = False

	def set_neighbor(self, neighbor):
		self.neighbors.append(neighbor)

	def mark_dfs(self, depth, root = False):
		global count
		self.marked = True
		count += 1
		if depth == 0:
			children = len(self.neighbors) - 1
			if not root:
				return children
			return min(children, 1)

		num_children = 0
		for neighbor in self.neighbors:
			if not neighbor.marked:
				mc = neighbor.mark_dfs(depth-1)
				if root:
					num_children = max(num_children,mc)
				else:
					num_children += mc

		return num_children

nodes = []
for i in range(n):
	node = Node()
	nodes.append(node)

def unmark_all():
	for node in nodes:
		node.marked = False

for i in range(n-1):
	u, v = [int(a)-1 for a in raw_input().split(" ")]
	nodes[u].set_neighbor(nodes[v])
	nodes[v].set_neighbor(nodes[u])

max_count = 0
for node in nodes:
	c = node.mark_dfs(k/2, True)
	if k % 2 == 1:
		count += c
	if count > max_count:
		max_count = count
	unmark_all()
	count = 0
	
print n - max_count



C Far Vertices HackerRank Solution


Copy Code Copied Use a different Browser

/* Enter your code here. Read input from STDIN. Print output to STDOUT */

#include <stdio.h>

long long b[1000],a[1000][1000],i,j,k,l,m,n,t,K;


long long makaj(long long ii, long long jj, long long hh)
{
long long vv=0,tt;

for(tt=0;tt<n;tt++)
 {
  if(a[tt][jj]<a[tt][ii] && a[tt][ii]<=hh) vv++; 
  if(a[tt][jj]>a[tt][ii] && a[tt][ii]<=K-hh) vv++;
 }

return vv;
} 


int main()
{

scanf("%lld %lld\n",&n,&K);

for(i=0;i<n;i++)
 for(j=0;j<n;j++) a[i][j] = 100000000;

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

for(i=0;i<n-1;i++)
{
 scanf("%lld %lld",&j,&l);
 a[j-1][l-1]=1;
 a[l-1][j-1]=1;
}

  for(k=0;k<n;k++)
for(i=0;i<n;i++)
 for(j=0;j<n;j++)
   if(a[i][j]> a[i][k] + a[k][j]) 
     {
     a[i][j] = a[j][i] = a[i][k]+a[k][j];
     }

m = 100000;

  for(i=0;i<n;i++)
    for(j=0;j<n;j++)
      if(a[i][j]==1)
       {
       for(l=K;l>=(K+1)/2;l--)
       k = makaj(i,j,l);
       if(n-k<m) m = n-k;       
       }



printf("%lld\n",m);

//for(i=0;i<n;i++)
// for(j=0;j<n;j++)
//  printf("%lld %lld -> %lld\n",i,j,a[i][j]);

return 0;
}

 

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)-SolutionKing Richard’s Knights – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionBalanced Brackets – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMinimum MST Graph – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionFavorite sequence – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTravelling Salesman in a Grid – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTwo Subarrays – HackerRank Solution
Tags: Cc++14Far Verticesfull 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
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

Counting Road Networks - HackerRank Solution

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

Superman Celebrates Diwali - 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)-SolutionKing Richard’s Knights – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionBalanced Brackets – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMinimum MST Graph – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionFavorite sequence – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTravelling Salesman in a Grid – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTwo Subarrays – 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
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Lovely Triplets – HackerRank Solution

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

Simplified Chess Engine II – HackerRank Solution

August 24, 2022
7
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

XOR Matrix – HackerRank Solution

August 24, 2022
10
Shining Girls Episode 5
Uncategorized

Shining Girls Episode 5 Release Date, Countdown

May 8, 2022
2

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