[ An Ac a Day ^_^ ] [kuangbin带你飞]专题八 生成树 UVA 10600 ACM Contest and Blackout 最小生成树+次小生成树

时间:2023-03-09 17:38:03
[ An Ac a Day ^_^ ] [kuangbin带你飞]专题八 生成树 UVA 10600	ACM Contest and Blackout 最小生成树+次小生成树

题意就是求最小生成树和次小生成树

 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#define cl(a,b) memset(a,b,sizeof(a))
#define debug(x) cerr<<#x<<"=="<<(x)<<endl
using namespace std;
typedef long long ll; const int maxn=1e2+;
const int inf=0x3f3f3f3f; int n,m;
int cost[maxn][maxn];
int pre[maxn],lowc[maxn];
int Max[maxn][maxn];
bool vis[maxn];
int used[maxn][maxn]; int mst()
{
int ans=;
cl(vis,false),cl(Max,);
vis[]=true,pre[]=,lowc[]=;
for(int i=; i<=n; i++)
{
lowc[i]=cost[][i];
pre[i]=;
}
for(int i=; i<=n; i++)
{
int minc=inf;
int p=-;
for(int j=; j<=n; j++)
{
if(!vis[j]&&minc>lowc[j])
{
minc=lowc[j];
p=j;
}
}
// if(minc==inf) return -1;
if(p==-) break;
ans+=minc;
for(int j=; j<=n; j++)
if(vis[j])
{
Max[j][p]=max(Max[j][pre[p]],cost[pre[p]][p]);
}
vis[p]=used[p][pre[p]]=used[pre[p]][p]=;
for(int j=; j<=n; j++)
{ if(!vis[j]&&lowc[j]>cost[p][j])
{
lowc[j]=cost[p][j];
pre[j]=p;
}
}
}
return ans;
} void solve()
{
int ans=mst();
int Min=inf;
for(int i=; i<=n; i++)
{
for(int j=; j<=n; j++)
{
if(cost[i][j]!=inf&&used[i][j]==)
{
Min=min(Min,ans+cost[i][j]-Max[i][j]);
}
}
}
printf("%d %d\n",ans,Min);
} int main()
{
int T;
scanf("%d",&T);
while(T--)
{
cl(cost,inf),cl(used,-);
scanf("%d%d",&n,&m);
for(int i=; i<=n; i++)
{
cost[i][i]=;
}
for(int i=; i<m; i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
cost[u][v]=cost[v][u]=w;
used[u][v]=used[v][u]=;
}
solve();
}
return ;
}
/* 2
5 8
1 3 75
3 4 51
2 4 19
3 2 95
2 5 42
5 4 31
1 2 9
3 5 66
9 14
1 2 4
1 8 8
2 8 11
3 2 8
8 9 7
8 7 1
7 9 6
9 3 2
3 4 7
3 6 4
7 6 2
4 6 14
4 5 9
5 6 10 */