链接:https://ac.nowcoder.com/acm/contest/7329/C
来源:牛客网
题目描述
DK 有一个无向图 G,这个无向图有 n 个点 m 条边
你需要确定一个大小为 n 的排列 a,使
∑
i
=
2
n
d
i
s
(
a
i
,
a
i
−
1
)
\sum_{i=2}^{n}dis(a_i, a_{i-1})
∑i=2ndis(ai,ai−1) 最大,求这个最大值
d
i
s
(
u
,
v
)
dis(u,v)
dis(u,v) 表示从 u 到 v 的路径的中最短的边的边权,若有多条路径,则选令
d
i
s
(
u
,
v
)
dis(u,v)
dis(u,v) 最大的路径
输入描述:
第一行两个正整数 n,m
接下来 m 行,每一行三个正整数 u,v,w 表示 u,v 之间有一条长度为 w 的边
输出描述:
仅一行,表示最大的 ∑i=2ndis(ai−1,ai)\sum\limits_{i=2}^n \operatorname{dis}(a_{i-1},a_i)i=2∑ndis(ai−1,ai)
示例1
输入
复制
2 1
1 2 3
输出
复制
3
说明
很显然,1,2 或者 2,1 都是合法的
备注:
对于 100%100%100% 的数据,1≤n,m≤5×1051 \leq n,m \leq 5 \times 10^51≤n,m≤5×105,1≤u,v≤n1\leq u,v\leq n1≤u,v≤n,1≤w≤1091 \leq w \leq 10^91≤w≤109,保证图联通
不是很理解为什么求最大生成树就是答案,先记录一下
- 大小为
n
的排列,相邻位置间连边,则有n
个点,n-1
条边 - 选出来的
n
个点和n-1
条边有两种可能- 联通,是一颗树
- 不连通,(实际上违背题意)
- 看别人的
ac
代码都是求最大生成树
#define debug
#ifdef debug
#include <time.h>
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)5e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO{
char print_f[105];
void read() {}
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K;
struct Node {
int u, v, w;
} a[MAXN];
int pre[MAXN];
int fa(int x) { return pre[x]==x ? x : (pre[x]=fa(pre[x])); }
void union_xy(int x, int y) {
x = fa(x), y = fa(y);
if(x ^ y) pre[y] = x;
}
signed main() {
#ifdef debug
freopen("test.txt", "r", stdin);
clock_t stime = clock();
#endif
read(n, m);
for(int i=1; i<=n; i++) pre[i] = i;
for(int i=1; i<=m; i++)
read(a[i].u, a[i].v, a[i].w);
sort(a+1, a+1+m, [&](Node&x, Node& y) { return x.w > y.w; });
K = n - 1;
ll ans = 0;
for(int i=1; i<=m && K; i++) {
int u = a[i].u, v = a[i].v;
if(fa(u) == fa(v)) continue ;
K --;
ans += a[i].w;
union_xy(u, v);
}
printf("%lld\n", ans);
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}