最小生成树问题,注意消去固定边时的方法:
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #define MAXN 800 #define MAXN1 300000 double x[MAXN], y[MAXN], w[MAXN1]; int n, p1, m, p[MAXN], u[MAXN1], v[MAXN1], r[MAXN1], vis[1010][1010]; int cmp(const void *_i, const void *_j) { int *i = (int *)_i; int *j = (int *)_j; return w[*i] > w[*j] ? 1 : -1; } int find(int x) {return p[x] == x ? x : p[x] = find(p[x]);} double kruskal() { double ans = 0; for(int i = 0; i <= n; i ++) p[i] = i; for(int i = 0; i < p1; i ++) r[i] = i; qsort(r,p1,sizeof(r[0]),cmp); for(int i = 0; i < p1; i ++) { int e = r[i]; int x1 = find(u[e]); int y1 = find(v[e]); if(x1 != y1){ans += w[e]; p[x1] = y1;} } return ans; } void init() { while(~scanf("%d",&n)) { memset(vis,0,sizeof(vis)); for(int i = 1; i <= n; i ++) scanf("%lf%lf",&x[i], &y[i]); scanf("%d",&m); for(int i = 0; i < m; i ++) { int z, c; scanf("%d%d",&z, &c); if(z > c) vis[c][z] = 1; else vis[z][c] = 1; } p1 = 0; for(int i = 1; i <= n; i ++) { for(int j = i+1; j <= n; j ++) { if(vis[i][j]) w[p1] = 0; else w[p1] = sqrt((x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j])); u[p1] = i; v[p1] = j; p1 ++; } } printf("%.2f\n",kruskal()); } } int main() { init(); return 0; }