哪里错了???

P3366 【模板】最小生成树

LYQ_666 @ 2024-05-03 21:43:03

#include <bits/stdc++.h> 
using namespace std;
int anc[10001],sum,ans,n,m;
struct E
{
    int u,v,w;
}e[10000];
bool c(E a,E b)
{
    return a.w<b.w;
}
int F(int x)
{
    if(anc[x]!=x) anc[x]=F(anc[x]);
    return anc[x];
}
int main()
{ 
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        cin>>e[i].u>>e[i].v>>e[i].w;
    }
    sort(e,e+m,c);
    for(int i=1;i<=n;i++)
    {
        anc[i]=i;
    }
    for(int i=0,fa,fb;i<m;i++)
    {   
        fa=F(e[i].u);
        fb=F(e[i].v);
        if(fa!=fb)
        {
        anc[fa]=fb;
        ans=ans+e[i].w;
        sum++;  
        }
        if(sum==n-1) break;
    }
    if(sum==n-1) cout<<ans;
    else cout<<"orz";
    return 0;
}

by LYQ_666 @ 2024-05-03 21:43:29

求改


by LYQ_666 @ 2024-05-03 21:44:17

79分


by sansesantongshun @ 2024-05-03 21:55:56

你数组开小了,好好看看数据范围qwq


by lcyxds @ 2024-05-03 22:02:40

AC

// test
#include <bits/stdc++.h> 
using namespace std;
int anc[10001],sum,ans,n,m;
struct E
{
    int u,v,w;
}e[200000];
bool c(E a,E b)
{
    return a.w<b.w;
}
int F(int x)
{
    if(anc[x]!=x) anc[x]=F(anc[x]);
    return anc[x];
}
int main()
{ 
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        cin>>e[i].u>>e[i].v>>e[i].w;
    }
    sort(e,e+m,c);
    for(int i=1;i<=n;i++)
    {
        anc[i]=i;
    }
    for(int i=0,fa,fb;i<m;i++)
    {   
        fa=F(e[i].u);
        fb=F(e[i].v);
        if(fa!=fb)
        {
        anc[fa]=fb;
        ans=ans+e[i].w;
        sum++;  
        }
        if(sum==n-1) break;
    }
    if(sum==n-1) cout<<ans;
    else cout<<"orz";
    return 0;
}

by LYQ_666 @ 2024-05-03 22:07:16

@sansesantongshun 谢谢


by LYQ_666 @ 2024-05-03 22:08:05

@lcyxds 谢谢


by LYQ_666 @ 2024-05-03 22:09:56

已过


|