处理何种问题:求解无向连通图的最小生成树,适合于稠密图,即点少边多的无向图。
性能:时间复杂度为 O(v * loge),v为点的个数,e为边的个数
原理:贪心策略。
实现步骤:正向模拟找连接点。即取任意一点,放入集合,找此点集合内最短的边且边的另一端点不在该集合内的点,将改点放入点集合内,重复此操作,直至所有点都在该集合内。
备注:因为得首先引入一点,设 0à1 为引入边,所以为了保持严谨性,点都从1àn,所以注意 0à1 为无效边。因为该图是一个稠密图,所以在建图时一般用邻接矩阵存图,所以点得极限在10000以内,否则,就该用克鲁斯卡尔来求了。
输入样例解释:
4 //点的个数
-1 1 4 1 // n*n的邻接表
1 -1 3 2
4 3 -1 5
1 2 5 -1
输出样例解释:
5 //最小生成树的值
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int MaxN=5100;///点的个数,极限是10000
int N,graph[MaxN][MaxN];/// 点数、矩阵存图
int ans,flag[MaxN];///标记数组,对于已在集合内的点标记好
struct node
{
int from,to,w;///保存最小生成树的形成路径
friend bool operator <(node n1,node n2)///重载运算符,自定义优先队列的排序规则
{
return n1.w>n2.w;
}
};
void init()///初始化函数
{
memset(graph,-1,sizeof(graph));
memset(flag,-1,sizeof(flag));
ans=0;
}
void Prim()
{
int n=0;
node temp,temp_1;
priority_queue<node>PQ;
temp.from=0;///存入初始边
temp.to=1;
temp.w=0;
PQ.push(temp);
while(n!=N)
{
while(flag[PQ.top().to]==0)///如果数据合理,此处不会爆栈
{
PQ.pop();
}
temp=PQ.top();
PQ.pop();
flag[temp.to]=0;///将点赋为 false
ans+=temp.w;
++n;
for(int i=1;i<=N;++i)
{
if(graph[temp.to][i]!=-1&&flag[i])
{
temp_1.from=temp.to;
temp_1.to=i;
temp_1.w=graph[temp.to][i];
PQ.push(temp_1);
}
}
}
}
int main()
{
while(~scanf("%d",&N))
{
init();///千万记得初始化
/**
如果给的是 点--点--权值 的形式,需要这样子建图
graph[x][y]=w;
graph[y][x]=w;
*/
for(int i=1;i<=N;++i)
{
for(int j=1;j<=N;++j)
{
scanf("%d",&graph[i][j]);
}
}
Prim();
printf("%d\n",ans);
}
return 0;
}
/**
4
-1 1 4 1
1 -1 3 2
4 3 -1 5
1 2 5 -1
*/