代码随想录: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;
  }
相关推荐
pluviophile_s14 小时前
数据结构:第6讲:树与二叉树
数据结构·笔记
来一碗刘肉面15 小时前
字符串模式匹配(朴素模式匹配算法与KMP算法)
数据结构·算法
code bean1 天前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
storyseek1 天前
前缀和实现Kogge-Stone算法
数据结构·算法
元Y亨H1 天前
深度解构:数据结构与算法的理论基石与工程演进
数据结构·算法
元Y亨H1 天前
数据结构与算法的通俗指南
数据结构·算法
2301_764441331 天前
用动力学系统(微分方程)为 Kernberg 的客体关系单元提供数学化的操作定义,把“自体—客体“这对心理结构建模成一个二维耦合系统
数据结构·python·算法·数学建模
ChaoZiLL1 天前
我读数据结构5-树
数据结构
冻柠檬飞冰走茶1 天前
PTA基础编程题目集 7-7 12-24小时制(C语言实现)
c语言·开发语言·数据结构·算法
雨落在了我的手上1 天前
Java数据结构(八):双链表的实现
数据结构