代码随想录:53、寻宝

53.寻宝

采用两种最小生成树算法分别来做一下

Prim算法

cpp 复制代码
  #include <iostream>
  #include<vector>
#include<climits>
  using namespace std;
  #define endl '\n'

  int main()
  {
    std::ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
   int v,e;
   int x,y,k;
   cin>>v>>e;
   
   vector<vector<int>>grid(v+1,vector<int>(v+1,10001));
  while(e--)
  {
      cin>>x>>y>>k;
      grid[x][y]=k;
      grid[y][x]=k;
  }
  vector<int> mindist(v+1,10001);
  vector<bool>isintree(v+1,0);
  
  for(int i=1;i<v;i++)
  {
      int cur=-1;
      int minval=INT_MAX;
      for(int j=1;j<=v;j++)
      if(!isintree[j]&&mindist[j]<minval)
      {
          minval=mindist[j];
          cur=j;
      }
      isintree[cur]=1;
      
      for(int j=1;j<=v;j++)
      {
          if(!isintree[j]&&grid[cur][j]<mindist[j])
           mindist[j]=grid[cur][j];
      }
  }
  int result=0;
  for(int i=2;i<=v;i++)
    result+=mindist[i];
    cout<<result;
  
    return 0;
  }

kruskal算法

cpp 复制代码
  #include <iostream>
  #include<vector>
#include<algorithm>
  using namespace std;
  #define endl '\n'

int n=10001;
vector<int>father(n,-1);
struct Edge
{
    int l,r,val;
};

void init()
{
    for(int i=0;i<n;i++)
    father[i]=i;
}
int find(int u)
{
    return u==father[u]?u:father[u]=find(father[u]);
}

void join(int u,int v)
{
    u=find(u);
    v=find(v);
    if(u==v)return ;
    father[v]=u;
}

  int main()
  {
    std::ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
   
   int v,e;
   int v1,v2,v3;
   vector<Edge>edges;
   int result_val=0;
   cin>>v>>e;
   while(e--)
   {
       cin>>v1>>v2>>v3;
       edges.push_back({v1,v2,v3});
       
   }
   
   sort(edges.begin(),edges.end(),[](const Edge&a,const Edge&b){return a.val<b.val;});
   
  vector<Edge> result;
  init();
  for(Edge edge:edges)
  {
      int x=find(edge.l);
      int y=find(edge.r);
      if(x!=y)
      {
          result.push_back(edge);
          result_val+=edge.val;
          join(x,y);
      }
  }
  
  cout<<result_val;
    return 0;
  }
相关推荐
如此这般英俊14 小时前
手搓Claude Code-第六章 subagent
数据结构·人工智能·python·语言模型·自然语言处理
Tairitsu_H15 小时前
[LC优选算法#17] 链表 | 合并 K 个升序链表 | K个⼀组翻转链表
数据结构·算法·链表
zwenqiyu18 小时前
非线性字符串数据结构串讲
数据结构·c++·学习·算法
东华万里18 小时前
第32篇 数据结构入门 单链表的增删查改实现
数据结构·链表
OOJO21 小时前
哈希表实现
数据结构·哈希算法·散列表
剑挑星河月1 天前
234. 回文链表
java·数据结构·算法·leetcode·链表
六bring个六1 天前
链表学习(常规链表)
数据结构·学习·链表
tachibana22 天前
hot100 回文链表(234)
java·网络·数据结构·leetcode·链表
aaaameliaaa2 天前
进制练习题【找出只出现一次的数字、交换两个变量(不创建临时变量)、统计二进制中1的个数、打印整数二进制的奇数位和偶数位、求两个数二进制中不同位的个数】
c语言·数据结构·笔记·算法
-dzk-2 天前
【系统架构设计师】案例分析篇
开发语言·数据结构·python·算法·架构·系统架构·架构设计