Title: https://www.luogu.org/problemnew/show/P1265
There are coordinates of n cities. Each city applies for and builds its own nearest city road. After that, they are regarded as a city.
Continue until all cities are one. Ask how many roads to build at least. In the title, if a ring is formed, the shortest one should be removed.
But cities ask for it one by one, and then it becomes a city. How can it form a ring
Train of thought: the meaning of this question is very strange. I didn't understand for a long time at the beginning, but I thought that it was required to generate the largest trees. In fact, it's just a minimal spanning tree.
Because there are many points, the graph will not be saved. When prim is used directly, dist function is used.
Note that in the dist function, x and y are integers. First, convert them to double. Some of the questions don't matter. This one is WA. Pay attention to the following.
1 #include<cstdio> 2 #include<cstdlib> 3 #include<map> 4 #include<set> 5 #include<cstring> 6 #include<algorithm> 7 #include<vector> 8 #include<cmath> 9 #include<stack> 10 #include<queue> 11 #include<iostream> 12 13 #define inf 0x3f3f3f3f 14 using namespace std; 15 typedef long long LL; 16 typedef pair<int, int> pr; 17 18 const int maxn = 5005; 19 int n; 20 struct node{ 21 int x, y; 22 }city[maxn]; 23 //double g[maxn][maxn]; 24 double d[maxn]; 25 bool vis[maxn]; 26 double ans = 0; 27 28 double dist(int i, int j) 29 { 30 return sqrt((double)(city[i].x - city[j].x) * (city[i].x - city[j].x) + (double)(city[i].y - city[j].y) * (city[i].y - city[j].y)); 31 } 32 33 void prim(int st) 34 { 35 vis[st] = true; 36 d[st] = 0; 37 for(int i = 1; i <= n; i++){ 38 d[i] = dist(st, i); 39 } 40 for(int t = 1; t < n; t++){ 41 double min = inf; 42 int minid; 43 for(int i = 1; i <= n; i++){ 44 if(!vis[i] && d[i] < min){ 45 min = d[i]; 46 minid = i; 47 } 48 } 49 vis[minid] = true; 50 ans += min; 51 for(int i = 1; i <= n; i++){ 52 if(d[i] > dist(minid, i)){ 53 d[i] = dist(minid, i); 54 } 55 } 56 } 57 } 58 59 int main() 60 { 61 scanf("%d", &n); 62 memset(d, 0x3f, sizeof(d)); 63 for(int i = 1; i <= n; i++){ 64 //par[i] = i; 65 scanf("%d%d", &city[i].x, &city[i].y); 66 } 67 // for(int i = 1; i <= n; i++){ 68 // for(int j = i + 1; j <= n; j++){ 69 // g[i][j] = g[j][i] = dist(i, j); 70 // //printf("%lf\n", g[i][j]); 71 // } 72 // } 73 74 prim(1); 75 printf("%.2lf\n", ans); 76 return 0; 77 }