Far Vertices


Problem Statement :


You are given a tree that has N vertices and N-1 edges. Your task is to mark as small number of vertices as possible, such that, the maximum distance between two unmarked vertices is less than or equal to K. Output this value. Distance between two vertices i and j is defined as the minimum number of edges you have to pass in order to reach vertex i from vertex j.

Input Format
The first line of input contains two integers N and K. The next N-1 lines contain two integers (ui,vi) each, where 1 <= ui,vi <= N. Each of these lines specifies an edge.
N is no more than 100. K is less than N.

Output Format
Print an integer that denotes the result of the test.



Solution :



title-img


                            Solution in C :

In C++ :






#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;
}








In Java :








import java.util.LinkedList;
import java.util.Scanner;

public class Solution {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int k = scanner.nextInt();
		LinkedList[] adjacencyList = new LinkedList[n];
		for (int i = 0; i < n; i++) {
			adjacencyList[i] = new LinkedList<Integer>();
		}
		for (int i = 0; i < n - 1; i++) {
			int node1 = scanner.nextInt();
			int node2 = scanner.nextInt();
			node1--;
			node2--;
			adjacencyList[node1].add(node2);
			adjacencyList[node2].add(node1);
		}
		int[][] farMatrix = new int[n][n];
		for (int i = 0; i < n; i++) {
			LinkedList<Integer> queue = new LinkedList<Integer>();
			LinkedList<Integer> queuedistance = new LinkedList<Integer>();
			boolean explored[] = new boolean[n];
			for (int j = 0; j < n; j++) {
				explored[j] = false;
			}
			queue.add(i);
			queuedistance.add(0);
			explored[i] = true;
			while (queue.isEmpty() == false) {
				int node = queue.removeFirst();
				int distance = queuedistance.removeFirst();
				farMatrix[i][node] = distance;
				for (Object adj : adjacencyList[node]) {
					Integer adjNode = (Integer) adj;
					if (explored[adjNode] == false) {
						queue.add(adjNode);
						queuedistance.add(distance + 1);
						explored[adjNode] = true;
					}
				}
			}
		}
		int count = 0;
		while (true) {
			int longestDistance = -1;
			int longestI = -1, longestJ = -1;
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					if (farMatrix[i][j] > longestDistance) {
						longestDistance = farMatrix[i][j];
						longestI = i;
						longestJ = j;
					}
				}
			}
			if (longestDistance <= k) {
				break;
			}
			count++;
			int iCount = 0;
			for (int i = 0; i < n; i++) {
				if (farMatrix[longestI][i] > k) {
					iCount++;
				}
			}
			int jCount = 0;
			for (int i = 0; i < n; i++) {
				if (farMatrix[longestJ][i] > k) {
					jCount++;
				}
			}
			// remove longestI
			if (iCount > jCount) {
				for (int i = 0; i < n; i++) {
					farMatrix[longestI][i] = 0;
					farMatrix[i][longestI] = 0;
				}
			} else {
				for (int i = 0; i < n; i++) {
					farMatrix[longestJ][i] = 0;
					farMatrix[i][longestJ] = 0;
				}
			}
		}
		System.out.println(count);

	}

}








In C :






#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;
}








In Python3 :






#!/bin/python3

import os
import sys
from collections import Counter

def farVertices(n, k, edges):
    tree = {}
    for edge in edges:
        tree[edge[0],edge[1]] = 1
        tree[edge[1],edge[0]] = 1
    tree_paths = len(tree)
    cont_flag = True
    while cont_flag:
        for edge in edges:
            matches = {x:y for x,y in tree.items() if edge[1] == x[0]}
            for match in matches.keys():
                if (edge[0],match[1]) not in tree.keys() and edge[0] != match[1]:
                    tree[edge[0],match[1]] = matches[match] + 1
                    tree[match[1],edge[0]] = matches[match] + 1
            matches = {x:y for x,y in tree.items() if edge[0] == x[1]}
            for match in matches.keys():
                if (edge[1],match[0]) not in tree.keys() and edge[1] != match[0]:
                    tree[edge[1],match[0]] = matches[match] + 1
                    tree[match[0],edge[1]] = matches[match] + 1
        if len(tree) == tree_paths:
            cont_flag = False
        tree_paths = len(tree)
    removed = 0
    cont_flag = True
    while cont_flag:
        matches = [x[0] for x,y in tree.items() if y>k]
        if len(matches)==0:
            cont_flag = False
        else:
            removed += 1
            match_count = Counter(matches)
            maxcount = max([y for x,y in match_count.items()])
            match_max = [x for x,y in match_count.items() if y==maxcount]
            remove_node = match_max[0]
            nodes_to_remove = [x for x in tree.keys() if 
                                 x[0]==remove_node or x[1]==remove_node]
            print(nodes_to_remove)
            for node in nodes_to_remove:
                del tree[node]
    return removed
                    
            

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

    nk = input().split()

    n = int(nk[0])

    k = int(nk[1])

    edges = []

    for _ in range(n-1):
        edges.append(list(map(int, input().rstrip().split())))

    result = farVertices(n, k, edges)

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

    fptr.close()
                        








View More Similar Problems

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →