最小生成树算法,用的prim,代码有点臃肿,超时了,后面再修改
unordered_set<int>visited;
unordered_set<int>q;
int n, m;
int dis ;
unordered_map<int, vector<vector<int>>>m1;
void dfs()
{
while (visited.size() != n) //直到遍历所有节点
{
int tmp = INT_MAX;
int tmp1 = 0;
for(auto i:visited)
for (auto j : m1[i])
{
if (j[1] < tmp&&visited.find(j[0])== visited.end())
{
tmp = j[1];
tmp1 = j[0];
}
}
visited.insert(tmp1);
dis += tmp;
}
}
int main()
{
cin >> n >> m;
int u,v,e;
for (int i = 0; i < m; ++i)
{
cin >> u >> v >> e;
m1[u].push_back({ v,e });
m1[v].push_back({ u,e });
q.insert(e);
}
dis = 0;
visited.insert(1);
dfs();
cout << dis << endl;
}