3 1.0 1.0 2.0 2.0 2.0 4.0
3.41
kruskal:
#include<cstdio> #include<cstring> #include<cmath> #define mem(a, b) memset(a, (b), sizeof(a)) #define Wi(a) while(a--) #define Si(a) scanf("%d", &a) #define Pi(a) printf("%d\n", (a)) #define INF 0x3f3f3f #include<algorithm> using namespace std; int per[150]; int n; double x[150],y[150]; void init(){ for(int i = 0; i <= n; i++) per[i] = i; } struct node{ int from, to; double val; }p[10010]; bool operator < (node a, node b) { return a.val < b.val; } int find(int x) { return x == per[x] ? x : (per[x] = find(per[x])); } bool join(int x, int y) { int fx = find(x); int fy = find(y); if(fx != fy) { per[fx] = fy; return true; } return false; } int main(){ while(Si(n)==1) { init(); double ans = 0.0; int i, j, k; for(i = 1; i <= n; i++) { scanf("%lf%lf", &x[i], &y[i]); } for(i = 1,k = 0; i <= n; i++) { for(j = i+1; j <= n; j++) { double d = sqrt( 1.0*(x[i]-x[j])*(x[i]-x[j]) + 1.0*(y[i]-y[j])*(y[i]-y[j])); p[k].from = i; p[k].to = j; p[k].val = d; k++; } } sort(p, p+k); for(i = 0; i < k; i++) { if(join(p[i].from, p[i].to)) ans += p[i].val; } printf("%.2lf\n", ans); } return 0; }
prim:
#include<cstdio> #include<cstring> #include<cmath> #define mem(a, b) memset(a, (b), sizeof(a)) #define Wi(a) while(a--) #define Si(a) scanf("%d", &a) #define Pi(a) printf("%d\n", (a)) #define Pf(a) printf("%.2lf\n", (a)) #define INF 0x3f3f3f double map[150][150]; int n; int vis[150]; double d[150], x[150], y[150]; void prim() { mem(vis, 0); int i,j,k; for(i = 1; i <= n; i++) d[i] = map[1][i]; vis[1] = 1; double minn, ans = 0.0; for(i = 1; i < n; i++) { k = 1; minn = INF; for(j = 1; j <= n; j++) { if(!vis[j] && d[j] < minn) { minn = d[j]; k = j; } } vis[k] = 1; ans += minn; for(j = 1; j <= n; j++) { if(!vis[j] && d[j] > map[j][k]) d[j] = map[j][k]; } } Pf(ans); } int main() { while(Si(n)==1){ int i,j,k; for(i = 1; i <= n; i++) { for(j = 1; j <= n; j++) { map[i][j] = map[j][i] = (i==j) ? 0 : INF; } } for(i = 1; i <= n; i++) { scanf("%lf%lf", &x[i], &y[i]); } for(i = 1; i <= n; i++) { for(j = 1; j <= n; j++) { map[i][j] = sqrt( (x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j])); } } prim(); } return 0; }