代码随想录: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;
  }
相关推荐
熬了夜的程序员1 天前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
立志成为大牛的小牛1 天前
数据结构——四十一、分块查找(索引顺序查找)(王道408)
数据结构·学习·程序人生·考研·算法
前端小L1 天前
二分查找专题(九):“降维”的魔术!将二维矩阵“拉平”为一维
数据结构·算法
她说人狗殊途1 天前
时间复杂度(按增长速度从低到高排序)包括以下几类,用于描述算法执行时间随输入规模 n 增长的变化趋势:
数据结构·算法·排序算法
Miraitowa_cheems1 天前
LeetCode算法日记 - Day 102: 不相交的线
数据结构·算法·leetcode·深度优先·动态规划
野生技术架构师1 天前
盘一盘Redis的底层数据结构
数据结构·数据库·redis
Miraitowa_cheems1 天前
LeetCode算法日记 - Day 101: 最长公共子序列
数据结构·算法·leetcode·深度优先·动态规划
北冥湖畔的燕雀1 天前
std之list
数据结构·c++·list
南方的狮子先生1 天前
【C++】C++文件读写
java·开发语言·数据结构·c++·算法·1024程序员节
Alex艾力的IT数字空间1 天前
完整事务性能瓶颈分析案例:支付系统事务雪崩优化
开发语言·数据结构·数据库·分布式·算法·中间件·php