最小生成树模板
//最小生成树 (图论) 每次选最小的边,不能成环
#include<bits/stdc++.h>
using namespace std;
int n,m,fa[200100];
struct node
{
int u,v,w;
}e[200100];
int find(int x)
{
return (fa[x]==x?x:fa[x]=find(fa[x]));
}
bool cmp(node a,node b)
{
return a.w<b.w;
}
int kruskal()
{
int cnt=0,ans=0;
for(int i=1;i<=m;i++)
{
int u=e[i].u,v=e[i].v,w=e[i].w;
//判断是否能选 并查集
//如果两点已连通则不能选
int fu=find(u),fv=find(v);
if(fu!=fv)
{
fa[fu]=fv;
cnt++;
ans+=w;
}
if(cnt==n-1) return ans;
}
return -1;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++) cin>>e[i].u>>e[i].v>>e[i].w;
for(int i=1;i<=n;i++) fa[i]=i;
sort(e+1,e+m+1,cmp);
int res=kruskal();
if(res==-1) cout<<"orz";
else cout<<res;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int mod=998244353;
int t,n,a[2010],tt,vis[2010];
ll c[5010][5010],dis[2010][2010];
struct node
{
int id;
ll dis;
bool operator <(const node &b)const
{
return dis>b.dis;
}
};
vector<node>e[2010];
//朴素 prim O(n^2)
/*ll prim()
{
int pos,mn;
ll ans=0;
memset(vis,0,sizeof(vis));
vis[1]=1;
for(int i=1;i<=n;i++) mnd[i]=dis[1][i];
for(int i=1;i<=n;i++)
{
mn=1e9;
for(int j=1;j<=n;j++)//每次寻找当前最优的点
{
if(!vis[j]&&mn>mnd[j])
{
mn=mnd[j];
pos=j;
}
}
if(mn==1e9) break;
ans=(ans+mn)%mod;
vis[pos]=1;
for(int j=1;j<=n;j++)
if(!vis[j]&&mnd[j]>dis[pos][j]) mnd[j]=dis[pos][j];
}
return ans;
}*/
//堆优化 O(nlogn)
priority_queue<node>q;
ll prim()
{
while(!q.empty()) q.pop();
int cnt=0;
ll ans=0;
memset(vis,0,sizeof(vis));
vis[1]=1;
for(node i:e[1]) q.push(i);
while(!q.empty())
{
node x=q.top();//每次取出最优的点
q.pop();
if(!vis[x.id])
{
vis[x.id]=1;
ans=(ans+x.dis)%mod;
}
for(node i:e[x.id])
if(!vis[i.id]) q.push(i);
}
return ans;
}
int main()
{
return 0;
}
kruskal适合点多边少,prim适合点少边多