最小生成树prim代码输出错了
  • 板块题目总版
  • 楼主jyulong
  • 当前回复11
  • 已保存回复11
  • 发布时间2024/8/15 08:23
  • 上次更新2024/8/15 10:30:36
查看原帖
最小生成树prim代码输出错了
1351616
jyulong楼主2024/8/15 08:23
#include<bits/stdc++.h>
using namespace std;
struct edge
{
	int to;
	int weight;
};
vector<edge> head[1001];
bool operator<(const edge &a,const edge &b)
{
	return a.weight>b.weight;
}
priority_queue<edge> q;
bool vis[1000];
int main()
{
	int i,j,k,u,v,n,ans=0;
	edge e;
	cin>>n;
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=n;j++)
		{
			cin>>k;
			if(k>0)
			{
				head[i].push_back({j,k});
			}
		}
	}
	vis[1]=1;
	for(i=0;i<head[1].size();i++)
	{
		q.push(head[1][i]);	
	} 
	for(i=1;i<n;i++)
	{
		while(!q.empty())
		{
			e=q.top();
			q.pop();
			if(!vis[e.to])
			{
				ans+=e.weight;
				vis[e.to]=1;
				break;
			}
		}
	}
	u=e.to;
	for(j=0;j<head[u].size();j++)
	{
		if(!vis[head[u][j].to])
		{
			q.push(head[u][j]);
		}
	}
	cout<<ans;
	return 0;
}
2024/8/15 08:23
加载中...