KS_tips_CN @ 2021-12-16 16:49:51
用的Kruskal,先放代码
//#include<bits/stdc++.h>
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<stack>
#include<list>
#include<map>
#include<set>
#include<cmath>
#include<cstring>
#include<queue>
#include<algorithm>
#include<vector>
#define ll long long
#define reg register int
#define gc getchar()
#define MAXN 20001//边的数量
#define MAXM 5001 //顶点数量
using namespace std;
int m,n;
int fth[MAXM];
ll sum;
inline ll read(void);
inline int find(int x){
if(fth[x]==x) return x;
fth[x]=find(fth[x]);
return fth[x];
}
struct edge{
int from,to,len;
}a[MAXN];
inline bool cmp( edge a , edge b );
int main(void){
n=read();//节点
m=read();//无向边
for(reg i=1;i<=m;i++) {
a[i].from = read() ;
a[i].to = read() ;
a[i].len = read() ;
}
//在这里读入所有无向边
sort(a+1,a+1+m,cmp);
//把所有边依照边长进行排序
for(reg i=1;i<=n;i++) fth[i]=i;
//并查集初始化
int k=0;
int from_,to_;
for(reg i=1;i<=m;i++){
from_=find(a[i].from);
to_=find(a[i].to);
if(from_!=to_){
//选择这一条边
k++;
fth[from_]=to_;
sum+=a[i].len;
if(k==n-1) break;
}
}
if(k<n-1) cout<<"orz"<<endl;
else cout<<sum<<endl;
return 0;
}
inline ll read(void){
ll x=0,f=0;
char ch=gc;
while(!isdigit(ch))
f|=(ch=='-'),ch=gc;
while(isdigit(ch))
x=(x<<1)+(x<<3)+(ch^48),ch=gc;
return f ? -x : x ;
}
inline bool cmp( edge a , edge b ){
return a.len < b.len ;
}
8,9是WA 10是MLE
求应该怎样优化
by rxjdasiwzl @ 2021-12-16 17:04:21
@KS_tips_CN 数组开小了,MAXN
是
by KS_tips_CN @ 2021-12-16 17:06:43
@rxjdasiwzl
改完就过了!非常感谢
(话说为什么改之前还有MLE改之后就AC……
by rxjdasiwzl @ 2021-12-16 17:16:04
@KS_tips_CN 越界了确实有可能 MLE 的