-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathKCentersProblem.cpp
More file actions
78 lines (68 loc) · 1.39 KB
/
KCentersProblem.cpp
File metadata and controls
78 lines (68 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Java program for the above approach
import java.util.*;
class GFG{
static int maxindex(int[] dist, int n)
{
int mi = 0;
for(int i = 0; i < n; i++)
{
if (dist[i] > dist[mi])
mi = i;
}
return mi;
}
static void selectKcities(int n, int weights[][],
int k)
{
int[] dist = new int[n];
ArrayList<Integer> centers = new ArrayList<>();
for(int i = 0; i < n; i++)
{
dist[i] = Integer.MAX_VALUE;
}
// Index of city having the
// maximum distance to it's
// closest center
int max = 0;
for(int i = 0; i < k; i++)
{
centers.add(max);
for(int j = 0; j < n; j++)
{
// Updating the distance
// of the cities to their
// closest centers
dist[j] = Math.min(dist[j],
weights[max][j]);
}
// Updating the index of the
// city with the maximum
// distance to it's closest center
max = maxindex(dist, n);
}
// Printing the maximum distance
// of a city to a center
// that is our answer
System.out.println(dist[max]);
// Printing the cities that
// were chosen to be made
// centers
for(int i = 0; i < centers.size(); i++)
{
System.out.print(centers.get(i) + " ");
}
System.out.print("\n");
}
// Driver Code
public static void main(String[] args)
{
int n = 4;
int[][] weights = new int[][]{ { 0, 4, 8, 5 },
{ 4, 0, 10, 7 },
{ 8, 10, 0, 9 },
{ 5, 7, 9, 0 } };
int k = 2;
// Function Call
selectKcities(n, weights, k);
}
}