代码随想录: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;
  }
相关推荐
Dfreedom.1 天前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
知花实央l1 天前
【算法与数据结构】拓扑排序实战(栈+邻接表+环判断,附可运行代码)
数据结构·算法
吃着火锅x唱着歌1 天前
LeetCode 410.分割数组的最大值
数据结构·算法·leetcode
AI科技星1 天前
垂直原理:宇宙的沉默法则与万物运动的终极源头
android·服务器·数据结构·数据库·人工智能
QuantumLeap丶1 天前
《数据结构:从0到1》-05-数组
数据结构·数学
violet-lz1 天前
数据结构八大排序:希尔排序-原理解析+C语言实现+优化+面试题
数据结构·算法·排序算法
草莓工作室1 天前
数据结构9:队列
c语言·数据结构·队列
violet-lz1 天前
数据结构八大排序:堆排序-从二叉树到堆排序实现
数据结构·算法
爱学习的小鱼gogo1 天前
python 单词搜索(回溯-矩阵-字符串-中等)含源码(二十)
开发语言·数据结构·python·矩阵·字符串·回溯·递归栈
浮灯Foden1 天前
算法-每日一题(DAY18)多数元素
开发语言·数据结构·c++·算法·leetcode·面试