omclude @ 2024-02-21 17:12:27
提交记录
Code:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
using ll = long long;
using LL = ll;
const int N = 5e3 + 10;
const int M = 2e5 + 5;
const int INF = 0x7fffffff;
inline void IOS() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
}
template <typename T>
void read(T &x) {
x = 0; char c = getchar(); int f = 0;
for (; !isdigit(c); c = getchar())
f |= c == '-';
for (; isdigit(c); c = getchar())
x = x * 10 + (c ^ '0');
if (f) x = -x;
}
template <typename T, typename ... Args>
void read(T& a, Args&... args) {
read(a), read(args...);
}
template <typename T>
void write(T x, char ed = '\n') {
if (x < 0) putchar('-'), x = -x;
static short st[30], tp;
do st[++tp] = x % 10, x /= 10; while (x);
while (tp) putchar(st[tp--] | '0');
putchar(ed);
}
template <typename T, typename ... Args>
void write(T& a, Args&... args) {
write(a), write(args...);
}
void Solve();
void merge(int a, int b);
int find(int a);
struct Edge{
int u, v, w, nxt;
bool operator < (const Edge b) const {
return w < b.w;
}
}E[M];
int head[N], cnt = 0;
void add(const Edge a)//加边,u起点,v终点,w边权
{
E[++cnt] = Edge{a.u, a.v, a.w, head[a.u]};
head[a.u] = cnt;
}
int n, m, ans = 0;
int u[N], fa[N];
signed main() {
IOS();
Solve();
return 0;
}
void Solve() {
read(n, m);
for(int i = 1; i < m; ++i) {
int u, v, w;
read(u, v, w);
add(Edge{u, v, w});
}
sort(E + 1, E + n + 1);
for(int i = 1; i <= n; ++i) {
fa[i] = i;
}
int ans = 0, tot = 0;
for(int i = 1; i <= m; ++i) {
int x = E[i].u, y = E[i].v;
if(find(x) != find(y)) {
ans += E[i].w;
tot += 1;
merge(x, y);
if(tot == n - 1) break;
}
}
if(ans == 0) puts("orz");
else write(ans);
}
void merge(int a, int b) {
fa[find(a)] = find(b);
}
int find(int a) {
while(a != fa[a]) a = fa[a] = fa[fa[a]];
return a;
}
by zhouzihang1 @ 2024-02-21 17:30:00
@LStylus 你好像没有输入完
by jianhe @ 2024-02-22 11:20:57
这道题是双向边。
@LStylus
by jianhe @ 2024-02-22 11:22:41
并且应该是 for(int i=1;i<=m;i++)
,少了一个等号。
@LStylus