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

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →