社区讨论

神秘kruskal TLE最后一个点球条

P3366【模板】最小生成树参与者 2已保存回复 3

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
3 条
当前快照
1 份
快照标识符
@mhjawufa
此快照首次捕获于
2025/11/03 23:34
4 个月前
此快照最后确认于
2025/11/03 23:34
4 个月前
查看原帖
直接把边存堆里面了,没有用邻接表存边:
CPP
#include<bits/stdc++.h>
using namespace std;
const int MaxN=5000,MaxM=2e5;

struct EDGE
{
    int a,b,val;
    bool operator>(const EDGE& oth)const {return val>oth.val;}
};

priority_queue< EDGE,vector<EDGE>,greater<EDGE> > ed;
int m,n,ans;
int f[MaxN+5],cnt;

int query(int x)
{
    stack<int> FIX;
    while(f[x])
    {
        FIX.push(x);
        x=f[x];
    }
    while(!FIX.empty())
    {
        f[FIX.top()]=x;
        FIX.pop();
    }
    return x;
}

void com(int x,int y)
{
    if(query(x)==query(y))return;
    f[query(x)]=query(y);
}

int main()
{
    scanf("%d %d",&n,&m);
    while(m--)
    {
        int a,b,c;
        scanf("%d %d %d",&a,&b,&c);
        ed.push({a,b,c});
    }
    for(int i=1;i<n;++i)
    {
        if(ed.empty())
        {
            printf("orz\n");
            return 0;
        }
        while(query(ed.top().a)==query(ed.top().b))
        {
            ed.pop();
            cnt++;
        }
        ans+=ed.top().val;
        com(ed.top().a,ed.top().b);
        ed.pop();
    }
    printf("%d\n",ans);
    return 0;
}

回复

3 条回复,欢迎继续交流。

正在加载回复...