• 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

Repair Roads – HackerRank Solution

Repair Roads - 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

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

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


Copy Code Copied Use a different Browser

#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>

using namespace std;

#define MAXN 10000

int memo[MAXN][3];
vector<int> E[MAXN];

int solve(int x, int froot, int p) {
  int& ref = memo[x][froot];
  if(ref != -1) return ref;
  
  ref = froot == 1 ? 0 : 1;

  int children = 0;
  vector<int> C;
  for(int i = 0; i < E[x].size(); i++) {
    int v = E[x][i];
    if(v == p) continue;

    int res = solve(v, 0, x);
    ref += res;
    C.push_back(solve(v, 1, x) - res);
    children++;
  }
  sort(C.begin(), C.end());


  int r1 = ref;
  int charge = (froot == 1 ? 1 : 2);
  for(int i = 0; i < C.size(); i++) {
    r1 += C[i];
    if(i == charge) {
      r1++;
      charge += 2;
    }
    ref = min(ref, r1);
  }
  if(children == 0 && froot != 2) {
    ref = 0;
  }

//cout << x << ", " << froot << ", " << ref  << " (" << C.size() << ")" << endl;
  if(froot == 0) {
    int r2 = 0;
    for(int i = 0; i < E[x].size(); i++) {
      int v = E[x][i];
      if(v == p) continue;
      r2 += solve(v, 2, x);
    }
    ref = min(ref, r2);
  }

  return ref;
}

int main() {
  int T; cin >> T;
  for(int t = 1; t <= T; t++) {
    int N; cin >> N;

    for(int i = 0; i < N; i++) E[i].clear();
    for(int i = 1; i < N; i++) {
      int u, v; cin >> u >> v;
      E[u].push_back(v);
      E[v].push_back(u);
    }

    memset(memo, -1, sizeof(memo));
    cout << solve(0, false, -1) << endl;
  }
}

Java Repair Roads HackerRank Solution


Copy Code Copied Use a different Browser

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

public class Solution {
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";

	static void solve()
	{
		for(int T = ni();T >= 1;T--){
			int n = ni();
			int[] from = new int[n-1];
			int[] to = new int[n-1];
			for(int i = 0;i < n-1;i++){
				from[i] = ni();
				to[i] = ni();
			}
			int[][] g = packU(n, from, to);
			int[][] pars = parents(g, 0);
			int[] par = pars[0];
			int[] ord = pars[1];
			
			int[] des = new int[n];
			for(int i = n-1;i >= 0;i--){
				int cur = ord[i];
				int d = 0;
				for(int e : g[cur]){
					if(par[cur] != e)d = Math.max(d, des[e]);
				}
				des[cur] = d + 1;
			}
			
			int[][] dp = new int[n][2]; // not extended, extended
			boolean[] ex = new boolean[n];
			for(int i = n-1;i >= 0;i--){
				int cur = ord[i];
				int ct = 0;
				int sdp = 0;
				int sh = 0;
				boolean onch = false;
				for(int e : g[cur]){
					if(par[cur] != e){
//						if(cur == 11)tr(e, des[e], dp[e], ex[e]);
						if(des[e] >= 2){
							if(ex[e]){
								ct++;
								sdp += dp[e][1]-1;
							}else{
								sdp += dp[e][1];
							}
							sh++;
						}else{
							sdp += dp[e][0];
							onch = true;
						}
					}
				}
//				if(cur == 11){
//					tr(sdp, sh, onch);
//				}
				// 0 1 ex
				// 1 1 ex
				// 2 1 noex
				// 3 2 ex
				if(ct > 0){
					dp[cur][0] = dp[cur][1] = sdp + (ct+1)/2;
					if(ct%2 == 1)ex[cur] = true;
				}else{
					dp[cur][0] = sdp + (onch ? 1 : 0);
					dp[cur][1] = sdp + 1;
					ex[cur] = true;
					if(!onch)des[cur] = 1;
				}
//				tr(cur, sdp, ct, sh, dp[cur], ex[cur]);
			}
//			tr(dp);
//			tr(ex);
			out.println(dp[0][0]);
		}
	}
	
	public static int[][] parents(int[][] g, int root) {
		int n = g.length;
		int[] par = new int[n];
		Arrays.fill(par, -1);

		int[] q = new int[n];
		q[0] = root;
		for(int p = 0, r = 1;p < r;p++){
			int cur = q[p];
			for(int nex : g[cur]){
				if(par[cur] != nex){
					q[r++] = nex;
					par[nex] = cur;
				}
			}
		}
		return new int[][] { par, q };
	}
	
	static int[][] packU(int n, int[] from, int[] to) {
		int[][] g = new int[n][];
		int[] p = new int[n];
		for(int f : from)
			p[f]++;
		for(int t : to)
			p[t]++;
		for(int i = 0;i < n;i++)
			g[i] = new int[p[i]];
		for(int i = 0;i < from.length;i++){
			g[from[i]][--p[from[i]]] = to[i];
			g[to[i]][--p[to[i]]] = from[i];
		}
		return g;
	}
	
	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}
	
	static boolean eof()
	{
		try {
			is.mark(1000);
			int b;
			while((b = is.read()) != -1 && !(b >= 33 && b <= 126));
			is.reset();
			return b == -1;
		} catch (IOException e) {
			return true;
		}
	}
		
	static int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}
			
			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}
	
	static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}

 



Python 3 Repair Roads HackerRank Solution


Copy Code Copied Use a different Browser

import collections
import queue


def solve():
    n = int(input().strip())

    # read graph
    graph = dict((i, []) for i in range(0, n))

    for j in range(n - 1):
        x, y = [int(p) for p in input().strip().split()]
        graph[x].append(y)
        graph[y].append(x)

    # transform graph into tree
    level = 1

    root = 0
    q = queue.Queue()
    q.put((root, level, None))
    seen = set([])

    levels = collections.defaultdict(set)
    tree = {}

    while not q.empty():
        item, level, parent = q.get()
        levels[level].add(item)
        seen.add(item)

        tree[item] = dict(id=item, parent=parent, level=level, children=set([]),
                          leaf=None)

        for child in graph[item]:
            if child not in seen:
                q.put((child, level + 1, item))
                seen.add(child)
                tree[item]['children'].add(child)

    # print('Levels: %s' % levels)
    # print('Tree: %s' % tree)

    # count clusters
    clusters = 1
    has_items_in_cluster = False

    for level in sorted(levels.keys(), reverse=True):
        for item in levels[level]:
            tree_item = tree[item]
            if not tree_item['children']:  # leaf
                tree_item['leaf'] = True
            else:
                has_items_in_cluster = True

                branches = 0
                for child in tree_item['children']:
                    if not tree[child]['leaf']:
                        branches += 1

                # branches == 0 -> visit point and go up
                # branches == 1 -> visit downstream, point and go up
                # branches % 2 == 0 -> have (branches // 2) clusters
                # branches % 2 == 1 -> have  (branches // 2) clusters and go up
                if branches >= 2:
                    new_clusters = branches // 2

                    clusters += new_clusters
                    # print('New clusters: %d' % new_clusters)

                    if branches % 2 == 0:
                        has_items_in_cluster = False
                        # cluster will also include road up
                        parent = tree_item['parent']
                        if parent is not None:
                            # print('Cut %s and %s' % (item, parent))
                            tree[parent]['children'].remove(item)

            # print(tree[item])

    # print('Tree: %s' % tree)

    if not has_items_in_cluster:
        clusters -= 1  # last cluster was created but has no items

    print(clusters)


t = int(input().strip())

for tt in range(t):
    solve()



C Repair Roads  HackerRank Solution


Copy Code Copied Use a different Browser

#include<stdio.h>
#include<malloc.h>
#define null NULL
long count;
long n2;
long *st[2];

typedef struct N 
{
	long data;
	struct N * next;
}node;

long adj(node **ar,long p)
{
	/*long i=0;
	while(i<n2 && ar[p][i]!=1){i++;
	}
	
		if(i==n2)
		return 0;
	
	long temp=ar[p][i];
	if(t == 1)
	{
	ar[p][i]=-1;
	ar[i][p]=-1;
	
	}

//	printf("p=%ld  i=%ld",p,i);
	return i;*/
	
	node *t=ar[p];
	if(t==null)
	{
		return 0;
		
	}
	t=ar[p];
	ar[p]=ar[p]->next;
	long d=t->data;
//	printf("0-> %ld ",d);
	free(t);
	t=null;
	t=ar[d];
	if(ar[d]->data==p)
	{
		ar[d]=ar[d]->next;
		
	}
	else
	{
		node * prev=ar[d];
		t=ar[d]->next;
		while(t->data != p)
		{
//			printf(" d=  %ld",t->data);
		   t=t->next;
		   prev=prev->next;
		}
		prev->next=t->next;
	}
	free(t);
	t=null;
	
	return d;
	
}


void dfsvisit(node ** ar,long s)
{
	long v,v2;
	while(v=adj(ar,s))
	{
	//	printf("hello\n");
		dfsvisit(ar,v);
	//	printf("v=%ld  s=%ld",v,s);
		if(st[0][v]==0 && st[1][v]==0)
		{
			if(st[1][s]==0)
			{
			//	printf("hello");
				st[1][s]=0;
				st[0][s]=1;
			}
		}
		else if(st[0][v]==1)
		{
			if(st[0][s]==0)
			{
				st[0][s]=st[0][v];
				st[1][s]=st[1][v]+1;
			}
			else if(st[0][s]==1 && st[1][s]==0 )
			{
				st[0][s]=st[0][v];
				st[1][s]=st[1][v]+1;
			}
			
			else
			{
				count++;
				st[1][s]=-1;
				st[0][s]=0;
			}
		}
		
	//	printf("count=%ld",count);
	
	
	}
	}



int main()
{
	long t,n,a,b;
	scanf("%ld",&t);


	while(t--)
	{
		scanf("%ld",&n);
		node **ar=(node**)malloc(n*sizeof(node*));
		
	//	long **ar=(long**)calloc(n,sizeof(long*));
		st[0]=(long*)calloc(n,sizeof(long));
		st[1]=(long*)calloc(n,sizeof(long));
		
		long i=0;
		n2=n;
	while(n--)
		{
			//ar[i++]=(long*)calloc(n2,sizeof(long));
			
			ar[i++]=null;
			
		}
		n=n2;
		n--;
		while(n--)
		{
			scanf("%ld %ld",&a,&b);
			node *temp=(node*)malloc(sizeof(node));
		
			
		
			//ar[a][b]=1;
			//ar[b][a]=1;
		
			temp->next=ar[a];
			
			ar[a]=temp;
			ar[a]->data=b;
			temp=(node*)malloc(sizeof(node));
			temp->next=ar[b];
			ar[b]=temp;
			ar[b]->data=a;
		//	printf("ar[b]->data = %ld",ar[b]->data);
		}
		long s=0;
		n=n2;
		count=0;
		
		
	//	adj(ar,0);
		dfsvisit(ar,0); 
	
	count=count+st[0][0];
		
		printf("%ld\n",count);
		free(ar);
		ar=NULL;
		free(st[0]);
		
		free(st[1]);
	
		
		
		
		
	}
	return 0;
	
}

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionMaximizing Mission Points – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMini-Max Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTower Breakers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree: Huffman Decoding – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionReal Estate Broker – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3Repair Roads
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

Kth Ancestor - HackerRank Solution

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

ByteLandian Tours - 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)-SolutionMaximizing Mission Points – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMini-Max Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTower Breakers – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree: Huffman Decoding – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionReal Estate Broker – 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
5 BEST WAYS TO LIMIT YOUR SALT INTAKE
Health

5 BEST WAYS TO LIMIT YOUR SALT INTAKE

May 19, 2022
1
Updates

Tony Beets Net Worth 2022: How Rich Is the Gold Rush Star?

September 5, 2022
1
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Kth Ancestor – HackerRank Solution

May 26, 2022
77
Biography

Ajith Kumar Net Worth, Age, Height , Achivements and more

September 8, 2022
0

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