Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <vector>
- using namespace std;
- const int maxn = 1e5 + 10;
- const int INF = 1e9;
- vector<pair<int, double> > graph[maxn];
- int n, m;
- struct node {
- int idx;
- double cost;
- node () {}
- node(int _idx, double _cost) {
- idx = _idx;
- cost = _cost;
- }
- bool operator < (const node &tmp) const {
- return cost > tmp.cost;
- }
- };
- double prim() {
- priority_queue<node> pq;
- pq.push(node(0, 0));
- vector<double> dist(n, INF);
- vector<bool> visited(n, false);
- dist[0] = 0;
- double mst = 0;
- while(!pq.empty()) {
- node c = pq.top();
- pq.pop();
- if(visited[c.idx]) continue;
- visited[c.idx] = true;
- mst += c.cost;
- for(int i = 0; i < (int) graph[c.idx].size(); i++) {
- int neighbour = graph[c.idx][i].first;
- double weight = graph[c.idx][i].second;
- if(!visited[neighbour] and weight < dist[neighbour]) {
- pq.push(node(neighbour, weight));
- dist[neighbour] = weight;
- }
- }
- }
- return mst;
- }
- int main() {
- int t;
- cin >> t;
- while(t--) {
- cin >> n;
- vector<pair<double, double> > v;
- for(int i = 0; i < n; i++) {
- graph[i].clear();
- double a, b;
- cin >> a >> b;
- v.push_back(make_pair(a, b));
- }
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < n; j++) {
- if(i != j) {
- double dist = sqrt((v[i].first - v[j].first) * (v[i].first - v[j].first) + (v[i].second - v[j].second) * (v[i].second - v[j].second));
- graph[i].push_back(make_pair(j, dist));
- }
- }
- }
- printf("%.3lf\n", prim());
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement