//http://acm.hdu.edu.cn/showproblem.php?pid=1102
#include <bits/stdc++.h>
#define N 111
using namespace std;
int n;
int G[N][N];
int vis[N], lowcost[N];
int prime()//只与点有关O(n * n),适合稠密图
{
int sum = 0;
vis[1] = 1;
for (int i = 1; i <= n; i++)//初始化,与1相连的最小的权
lowcost[i] = G[1][i];
for (int i = 1; i <= n; i++)//找出与生成树集合相连的最小权值的边
{
int k, tmp = 1 << 20;
for (int j = 1; j <= n; j++)
if (!vis[j] && lowcost[j] < tmp)
tmp = lowcost[k = j];
if (tmp == 1 << 20)
break;
vis[k] = 1;
sum += tmp;
for (int j = 1; j <= n; j++)//更新
if (!vis[j] && G[k][j] < lowcost[j])
lowcost[j] = G[k][j];
}
return sum;
}
int main()
{
while (~scanf("%d", &n))
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
scanf("%d", &G[i][j]);
}
}
int Q;
scanf("%d", &Q);
for (int i = 0; i < Q; i++)
{
int a, b;
scanf("%d%d", &a, &b);
G[a][b] = G[b][a] = 0;
}
printf("%d\n", prime());
}
return 0;
}
最小生成树 - Prime()
最新推荐文章于 2021-11-16 21:13:23 发布