自己写的代码,所以可能思路会有点乱。
感觉是堆优化写错了,TLE了三个点,其他全AC
#include<bits/stdc++.h>
using namespace std;
int n,m,S;
int head[100010];
int from[200010];
int to[200010];
int nxt[200010];
int w[200010];
int b[100010];
int cnt=0;
struct node
{
int id,len;
bool operator <(const node &x)const
{
return x.len<len;
}
};
void add(int x,int y,int z)
{
from[++cnt]=x;
to[cnt]=y;
w[cnt]=z;
nxt[cnt]=head[x];
head[x]=cnt;
}
int f[100010];
int fa(int x)
{
if(f[x]==x) return x;
return f[x]=fa(f[x]);
}
priority_queue<node> q;
int prim()
{
int T=n-1;
int u=1;
int sum=0;
while(T--)
{
b[u]=1;
for(int i=head[u];i;i=nxt[i])
{
int v=to[i];
if(!b[v]&&fa(u)!=fa(v))
{
q.push((node){i,w[i]});
}
}
while(!q.empty())
{
node tmp=q.top();
q.pop();
if(fa(from[tmp.id])!=fa(to[tmp.id]))
{
//cout<<u<<":"<<from[tmp.id]<<" "<<to[tmp.id]<<" - "<<tmp.len<<"\n";
sum+=tmp.len;
f[fa(from[tmp.id])]=fa(to[tmp.id]);
u=to[tmp.id];
break;
}
}
}
return sum;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
add(x,y,z);
add(y,x,z);
}
for(int i=1;i<=n;i++) f[i]=i;
cout<<prim();
}