裸题,上模板就行,注意j ! = k
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<vector> #include<cstdio> #include<cassert> #include<iomanip> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define pi acos(-1) #define ll long long #define mod 1000000007 #define ls l,m,rt<<1 #define rs m+1,r,rt<<1|1 #pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; const double g=10.0,eps=1e-9; const int N=100+10,maxn=111117,inf=0x3f3f3f; int c[N][N],d[N],pre[N],n; int maxx[N][N]; bool vis[N],used[N][N]; int prim() { memset(vis,0,sizeof vis); memset(used,0,sizeof used); memset(maxx,0,sizeof maxx); for(int i=1;i<=n;i++) { pre[i]=1; d[i]=c[1][i]; } vis[1]=1; pre[1]=0; d[1]=0; int ans=0; for(int i=2;i<=n;i++) { int mind=inf,k; for(int j=1;j<=n;j++) { if(!vis[j]&&mind>d[j]) { mind=d[j]; k=j; } } vis[k]=1; ans+=mind; used[k][pre[k]]=used[pre[k]][k]=1; for(int j=1;j<=n;j++) { if(vis[j]&&j!=k)maxx[j][k]=maxx[k][j]=max(maxx[j][pre[k]],d[k]); if(!vis[j]&&d[j]>c[j][k]) { d[j]=c[j][k]; pre[j]=k; } } } return ans; } int smst(int mst) { int ans=inf; for(int i=1;i<=n;i++) { for(int j=i+1;j<=n;j++) { if(c[i][j]!=inf&&!used[i][j]) { ans=min(ans,mst+c[i][j]-maxx[i][j]); } } } return ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); int t,m; cin>>t; while(t--){ cin>>n>>m; for(int i=1;i<=n;i++) { c[i][i]=0; for(int j=i+1;j<=n;j++) c[i][j]=c[j][i]=inf; } while(m--){ int x,y,z; cin>>x>>y>>z; c[x][y]=c[y][x]=z; } int ans=prim(); cout<<ans<<" "<<smst(ans)<<endl; } return 0; }