Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <map>
- #include <cmath>
- typedef std::pair<int, int> point2d;
- typedef std::vector<int> iVec;
- std::vector<point2d> In;
- std::map<point2d, int> dist;
- std::map<int, int> min_e;
- std::vector<bool> used;
- int len( const point2d & A, const point2d & B ) { return (A.first - B.first) * (A.first - B.first) + (A.second - B.second) * (A.second - B.second); }
- std::pair<int, int> find_min( int a )
- {
- int lenn, min_l = -1, min_ind = -1;
- for (int b = 0; b < In.size(); b++)
- {
- if (a == b || used[b])
- continue;
- lenn = (!dist[{a, b}]) ? (dist[{a, b}] = dist[{b, a}] = len(In[a], In[b])) : dist[{a, b}];
- if ((lenn < min_l) || (min_l == -1))
- min_l = lenn, min_ind = b;
- }
- min_e[a] = min_ind + 1;
- return std::make_pair(min_ind, min_l);
- }
- int main()
- {
- int n = 0;
- scanf("%i", &n);
- int x = 0, y = 0, i, tmp = 1;
- long double res = 0;
- std::pair<int, int> best_p;
- used.resize(n);
- std::generate(used.begin(), used.end(), []() { return false; });
- int min_l = -1, min_ind = -1, lenn;
- // Prim
- i = n;
- while (i--)
- scanf("%i%i", &x, &y), In.push_back(point2d(x, y));
- // fill the mst
- used[0] = true;
- for (int size = n - 1; size; size--)
- {
- min_l = min_ind = -1;
- for (int a = 0; a < n; a++)
- {
- if (!used[a])
- continue;
- tmp = min_e[a] - 1;
- if (!min_e[a] || used[min_e[a] - 1])
- tmp = find_min(a).first;
- lenn = (!dist[{a, tmp}]) ? (dist[{a, tmp}] = dist[{tmp, a}] = len(In[a], In[tmp])) : dist[{a, tmp}];
- if ((lenn < min_l) || (min_l == -1))
- min_l = lenn, min_ind = tmp;
- }
- if (min_ind == -1)
- { printf("0");
- return 0; }
- used[min_ind] = true;
- res += sqrt(min_l);
- // recount if needed
- for (int a = 0; a < n; a++)
- if (used[a] && (!min_e[a] || used[min_e[a] - 1]))
- find_min(a);
- }
- //
- printf("%lf", res);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement