非递归求法不行吗?
查看原帖
非递归求法不行吗?
670826
NianFeng楼主2022/9/22 16:46

RT,下是10分代码

#include <bits/stdc++.h>
using namespace std;
const int N=200000;
int n,m,f[N];
struct road {
	int from,to;
	int time;
	bool operator<(const road r)const {
		return time<r.time;
	}
} r[N];
int find(int x) {
	int r=x;
	if(r!=f[r]) {
		r=f[r];
	}
	while(x!=f[x]) {
		int z=x;
		x=f[x];
		f[z]=r;
	}
	return r;
}
int main() {
	cin>>n>>m;
	for(int i=1; i<=n; i++)
		f[i]=i;
	for(int i=1; i<=m; i++)
		cin>>r[i].from>>r[i].to>>r[i].time;
	sort(r+1,r+m+1);
	for(int i=1; i<=m; i++) {
		int x=find(r[i].from),y=find(r[i].to);
		if(x!=y) f[x]=y,n--;
		if(n==1){
			cout<<r[i].time;
			return 0;
		}
	}
	cout<<-1;
	return 0;
}

改成这个就AC了

int find(int x){return f[x]==x?x:(f[x]=find(f[x]));}
2022/9/22 16:46
加载中...