社区讨论
37求调
P1807最长路参与者 2已保存回复 1
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 1 条
- 当前快照
- 1 份
- 快照标识符
- @mewm504b
- 此快照首次捕获于
- 2025/08/29 17:11 6 个月前
- 此快照最后确认于
- 2025/08/29 17:31 6 个月前
我看这题类似最短路打了个最短路后反过来的
CPP#include<bits/stdc++.h>
using namespace std;
struct node{
int x,y,z;
}e[500005];
int anc[1510];
int n,m;
int ans=0,cnt=0;
bool cmp(node a,node b){
return a.z>b.z;
}
int find(int x){
if(x!=anc[x]){
anc[x]=find(anc[x]);
}
return anc[x];
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
anc[i]=i;
}
for(int i=1;i<=m;i++){
scanf("%d%d%d",&e[i].x,&e[i].y,&e[i].z);
}
sort(e+1,e+m+1,cmp);
for(int i=1;i<=m;i++){
int fx,fy;
fx=find(e[i].x);
fy=find(e[i].y);
if(fx!=fy){
anc[fy]=fx;
ans+=e[i].z;
cnt++;
}
if(cnt==n) break;
}
if(cnt==n-1) cout<<ans;
else cout<<"-1";
return 0;
}
回复
共 1 条回复,欢迎继续交流。
正在加载回复...