← 返回 microsoft 的题目列表Implement K-Means Clustering
类型:online_judge
Coding: Implement K-Means Clustering
Given n data points in d dimensions and a target number of clusters k, implement K-Means and output the cluster label for each point.
Input (stdin)
Line 1: three integers n d k
Next n lines: d floating-point numbers per line representing a point
Last line: two numbers max_iter tol
Output (stdout)
Print n lines. Line i contains the cluster label (from 0 to k-1) assigned to point i.
Constraints
1 <= n <= 2000
1 <= d <= 20
1 <= k <= min(n, 50)
1 <= max_iter <= 200
tol >= 0 is the convergence threshold: stop if the maximum centroid movement between two iterations is <= tol.
Requirements
Initialization: use the first k points as initial centroids.
Assignment: assign each point to the nearest centroid by Euclidean distance; break ties by choosing the smallest cluster id.
Update: each centroid becomes the mean of points assigned to it.
Empty cluster: if a cluster gets no points, keep its centroid unchanged.
Test cases
See tests below.
Example
Input
6 2 2
0 0
0 1
1 0
10 10
10 11
11 10
100 0
Output
0
0
0
1
1
1