先求最小生成树
再遍历每一对顶点,如果该顶点之间的边属于最小生成树,则剪掉这对顶点在最小生成树里的最长路径
否则直接剪掉连接这对顶点的边~
用prim算法求最小生成树最长路径的模板~
#include<cstdio> #include<cstring> #include<algorithm> #include<vector> #include<cmath> using namespace std; const int maxn=1014; const int inf=1e9; double g[maxn][maxn],d[maxn],w[maxn]; int visit[maxn],N,S,P,pre[maxn]; double len[maxn][maxn];//表示点i,j在最小生成树上的最长路径 double c[maxn][maxn]; void init () { for (int i=0;i<maxn;i++) for (int j=0;j<maxn;j++) g[i][j]=inf,c[i][j]=0,len[i][j]=0; } double prim (int s) { fill (d,d+maxn,inf); fill (visit,visit+maxn,0); for (int i=1;i<=N;i++) pre[i]=i; d[s]=0; double ans=0; for (int i=1;i<=N;i++) { int u=-1,min=inf; for (int j=1;j<=N;j++) if (!visit[j]&&d[j]<min) { u=j; min=d[j]; } if (u==-1) return -1; visit[u]=1; ans+=d[u]; if (pre[u]!=u) c[u][pre[u]]=c[pre[u]][u]=1; for (int v=1;v<=N;v++) if (!visit[v]&&g[u][v]!=inf&&g[u][v]<d[v]) { d[v]=g[u][v]; pre[v]=u; } for (int v=1;v<=N;v++) if (visit[v]&&u!=v) len[u][v]=len[v][u]=max(len[pre[u]][v],d[u]); } return ans; } struct node { double x,y; }Node[maxn]; int main () { int T; scanf ("%d",&T); while (T--) { scanf("%d",&N); for (int i=1;i<=N;i++) scanf ("%lf %lf %lf",&Node[i].x,&Node[i].y,&w[i]); init (); for (int i=1;i<=N;i++) for (int j=i+1;j<=N;j++) g[i][j]=g[j][i]=sqrt((Node[i].x-Node[j].x)*(Node[i].x-Node[j].x)+(Node[i].y-Node[j].y)*(Node[i].y-Node[j].y)); double mst=prim(1); double Max=0; for (int i=1;i<=N;i++) for (int j=i+1;j<=N;j++) if (!c[i][j]) Max=max(Max,(w[i]+w[j])/(mst-len[i][j])); else Max=max(Max,(w[i]+w[j])/(mst-g[i][j])); printf ("%.2f ",Max); } return 0; }