# 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 :

```                            ```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.Scanner;

public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
for (int i = 0; i < n; i++) {
}
for (int i = 0; i < n - 1; i++) {
int node1 = scanner.nextInt();
int node2 = scanner.nextInt();
node1--;
node2--;
}
int[][] farMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
boolean explored[] = new boolean[n];
for (int j = 0; j < n; j++) {
explored[j] = false;
}
explored[i] = true;
while (queue.isEmpty() == false) {
int node = queue.removeFirst();
int distance = queuedistance.removeFirst();
farMatrix[i][node] = distance;
}
}
}
}
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

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

## Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

## Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

## Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

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

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