Kattis Problem - Freckles
作者:互联网
Kattis Problem - Freckles
题目类型:最小生成树
题意:
在纸上有 n 个点(坐标形式给出),可以用钢笔划线将点连接起来。现在需要用钢笔连线使得所有的点都连通,并使用墨水最少,画线使用墨水的值等于线的长度。
分析:
很明显是要求其最小生成树。在每两个点之间建边,长度为其之间的距离,然后使用 Prim 算法求其最小生成树。使用 Kruskal 算法会超时。
代码
static double[] x;
static double[] y;
static double[][] G;
public static void solve() throws IOException {
int m = nextInt();
init(m);
for (int i = 0; i < m; i++) {
x[i] = nextDouble();
y[i] = nextDouble();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
G[i][j] = getDis(x[i], y[i], x[j], y[j]);
}
}
double ans = prim(m);
pw.println(String.format("%.2f", ans));
}
public static double prim(int m) {
double[] dis = new double[m];
boolean[] vis = new boolean[m];
Arrays.fill(dis, INF);
double re = 0;
for (int i = 0; i < m; i++) {
int u = -1;
for (int j = 0; j < m; j++)
if (!vis[j] && (u == -1 || dis[u] > dis[j])) u = j;
vis[u] = true;
if (i != 0) re += dis[u];
for (int j = 0; j < m; j++) dis[j] = Math.min(dis[j], G[u][j]);
}
return re;
}
public static void init(int m) {
x = new double[m];
y = new double[m];
G = new double[m][m];
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
G[i][j] = (i == j ? 0 : INF);
}
public static double getDis(double x1, double y1, double x2, double y2) {
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
标签:Kattis,int,Freckles,++,static,double,new,Problem,dis 来源: https://blog.csdn.net/w_weirdo/article/details/119191930