1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include <cstdio> #include <algorithm> #include <cstring> using namespace std;
const int maxn=1010; const int inf=0x3f3f3f3f; bool vis[maxn]; int lowc[maxn]; int pre[maxn]; int cost[maxn][maxn]; int Max[maxn][maxn]; bool used[maxn][maxn]; int n,m;
int (int n) { int ans=0; memset(vis,false,sizeof(vis)); memset(Max,0,sizeof(Max)); memset(used,false,sizeof(used)); vis[0]=true; pre[0]=-1;
for (int i=1;i<n;i++) { lowc[i]=cost[0][i]; pre[i]=0; } lowc[0]=0; for (int i=1;i<n;i++) { int minc=inf; int p=-1; for (int j=0;j<n;j++) { if(!vis[j] && minc>lowc[j]) { minc=lowc[j]; p=j; } } ans+=minc; vis[p]=true; used[p][pre[p]]=used[pre[p]][p]=true; for (int j=0;j<n;j++) { if(vis[j] && j!=p) Max[j][p]=Max[p][j]=max(Max[j][pre[p]],lowc[p]); if(!vis[j] && lowc[j]>cost[p][j]) { lowc[j]=cost[p][j]; pre[j]=p; } } } return ans; }
int main() { int t; scanf("%d",&t); while (t--) { scanf("%d%d",&n,&m); int u,v,w; memset(cost,inf,sizeof(cost)); for (int i=0;i<m;i++) { scanf("%d%d%d",&u,&v,&w); u--,v--; cost[u][v]=w; cost[v][u]=w; } int res,ans; int maxx=inf; ans=Prim(n); for (int i=0;i<n;i++) { for (int j=i+1;j<n;j++) { if(!used[i][j]&& cost[i][j]!=inf && Max[i][j]<=cost[i][j]) { maxx=min(maxx,cost[i][j]-Max[i][j]); } } }
printf("%d %dn",ans,ans+maxx); } return 0; }
|
近期评论