hdu 1162 Eddy's picture(最小生成树Prim算法)

/* Author: ACb0y Date: 2010-9-15 Type: graph(MST prim) ProblemId: hdu 1162 Eddy's picture Result: AC */ #include <iostream> #include <cmath> using namespace std; #define inf 99999999999.9 struct Point { double x; double y; }; //顶点数 int n; //用来保存每个顶点的坐标 Point points[110]; //用邻接矩阵保存图 double g[110][110]; //记录第一个顶点到各个顶点的最小距离 double d[110]; //用来标记顶点是否进入了最小生成树的点的集合 int vis[110]; double dis(Point a, Point b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); } //最小生成树prim算法 void MST() { int i, j; for (i = 1; i <= n; i++) { d[i] = inf; } d[1] = 0; double ans = 0; memset(vis, 0, sizeof(vis)); //n个顶点分别入生成树 for (i = 1; i <= n; i++) { double Min = inf; int pos = -1; //查询当前最小的没有入生成树的最小的边 for (j = 1; j <= n; j++) if (!vis[j]) { if (d[j] < Min) { Min = d[j]; pos = j; } } //标记顶点入生成树 vis[pos] = 1; //记录代价 ans += Min; //更新各个顶点到生成树的距离 for (j = 1; j <= n; j++) { if (g[pos][j] < d[j]) { d[j] = g[pos][j]; } } } printf("%.2lf/n", ans); } int main() { int i, j; #ifndef ONLINE_JUDGE freopen("1162.txt", "r", stdin); #endif while (cin >> n) { for (i = 1; i <= n; i++) { cin >> points[i].x >> points[i].y; } for (i = 1; i <= n; i++) { for (j = i; j <= n; j++) { g[i][j] = g[j][i] = dis(points[i], points[j]); } } MST(); } return 0; }

你可能感兴趣的:(算法,struct,Graph,2010)