summaryrefslogtreecommitdiffstats
path: root/03-algorithms_on_graphs/05-minimum_spanning_tree/02-clustering/clustering.cpp
blob: 167dc5c121c9436afe9b8e48d99ae1ae545297e3 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cassert>
#include <vector>
#include <cmath>

using std::vector;
using std::pair;


struct Vertex
{
    int a;
    int b;
    double l;

    static int compare(Vertex &a, Vertex &b)
    {
        return (a.l < b.l);
    }

    void print()
    {
        std::cout << a << ";" << b << " " << l << std::endl;
    }
};

struct Point
{
    int x;
    int y;
    int parent;

    void print()
    {
        std::cout << x << ";" << y << " " << parent << std::endl;
    }
};

struct Points
{
    vector<Point> points;
    vector<Vertex> vertices;

    Points(int n) : points(n), vertices(n*n) { }

    void read(int i)
    {
        std::cin >> points[i].x >> points[i].y;
        points[i].parent = i;
    }

    void print()
    {
        for (int i = 0; i < points.size(); i++)
            points[i].print();
    }

    int find(int i)
    {
        if (points[i].parent == i)
            return i;
        points[i].parent = find(points[i].parent);
        return points[i].parent;
    }

    double solve(int k)
    {
        int x = 0;
        for (int i = 0; i < points.size(); i++) {
            for (int j = i + 1; j < points.size(); j++) {
                vertices[x].a = i;
                vertices[x].b = j;
                vertices[x].l =  sqrt(
                        (points[i].x - points[j].x) * (points[i].x - points[j].x)
                        +
                        (points[i].y - points[j].y) * (points[i].y - points[j].y)
                        );
                x += 1;
            }
        }
        vertices.resize(x);

        std::sort(vertices.begin(), vertices.end(), Vertex::compare);

        int n = 0;
        double result = 0.;
        for (int i = 0; i < vertices.size(); i++) {
            int realA = find(vertices[i].a);
            int realB = find(vertices[i].b);
            if (realA != realB) {
                if (n == points.size() - k) {
                    result = vertices[i].l;
                    break;
                }
                n += 1;
                points[realB].parent = realA;
            }
        }

        return result;
    }
};

int main() {
  size_t n;
  int k;
  std::cin >> n;
  Points points(n);
  for (size_t i = 0; i < n; i++)
      points.read(i);
  std::cin >> k;
  std::cout << std::setprecision(10) << points.solve(k) << std::endl;
}