最小生成树kruskal模板题37分求助
  • 板块学术版
  • 楼主南瓜桐
  • 当前回复11
  • 已保存回复11
  • 发布时间2022/8/4 22:20
  • 上次更新2023/10/27 16:58:33
查看原帖
最小生成树kruskal模板题37分求助
439327
南瓜桐楼主2022/8/4 22:20

评测记录
题目链接
我的代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
namespace wzl{
int n,m;
const int MAXM = (2e5 + 1)*2;
const int MAXN = 5e3  +1;
int fa[MAXN]={};
vector<int>fr,wt,to,nxt,head;
struct node{
	int ent;
	int num;
}a[MAXM]={};
int cnt=-1;
int ans = 0;
int stats = 0;
inline void add(int x,int y,int z){
	fr.push_back(x);
	to.push_back(y);
	wt.push_back(z);
	a[++cnt].ent = z;
	a[cnt].num = cnt;
	nxt.push_back(head[x]);
	head[x] = wt.size() - 1;
	return;
}
bool cmp(node x,node y){
	return x.ent < y.ent;
}
int getfa(int x){
	if(fa[x] != x){
		x = getfa(fa[x]);
	}else{
		return x;
	}
}
void merge(int a1,int b1){
	fa[getfa(a1)] = getfa(b1);
}
void kruckal(){
	stats = 0;
	sort(a+1,a+1+m,cmp);
	for(int i = 1; i <= n; ++i) fa[i] = i;
	for(int i = 1; i <= n; ++i){
		int x = a[i].num;
		int u = fr[x],v = to[x], w = wt[x];
		if(getfa(u) != getfa(v)){
			ans += w;
			merge(u,v);
			++stats;
//			cout<<"gc:"a<<u<<"->"<<v<<endl;
		}
		if(stats == n-1){
			break;
		}
	}
	
}
void main(){
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin>>n>>m;
	head.resize(n+1,-1);
	for(int i = 1; i <= m; ++i){
		int x,y,z;
		cin>>x>>y>>z;
		add(x,y,z);
	}
	kruckal();
	
	if(stats < n-1){
		cout<<"orz"<<endl;
	}else{
		cout<<ans;
	}
	return;
}
}


int main(){
	wzl::main();
	return 0;
}

下载样例 : https://s1.ax1x.com/2022/08/04/vmK3Y8.png 谢谢了

2022/8/4 22:20
加载中...