文章目录
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6d89f2f45789ce54e0254a884be98773.jpeg#pic_center)
F题
Agamemnon’s Odyssey
k>=2,答案为sum,k=1时答案为树的直径【dfs】
#include <bits/stdc++.h>
using namespace std;
// #pragma GCC optimize(3, "Ofast", "inline")
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
const int N = 2 * 1e5 + 10;
const int inf = 0x3f3f3f3f;
const int mod = 1e9;
#define IOS \
ios::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
ll n, k, tot, res, sum;
ll nex[2 * N], head[2 * N], to[2 * N], val[2 * N], dis[2 * N];
bool vis[2 * N];
void add(int u, int v, int w)
{
to[++tot] = v;
val[tot] = w;
nex[tot] = head[u];
head[u] = tot;
}
void dfs(int x)
{
vis[x] = 1;
for (int i = head[x]; ~i; i = nex[i])
{
ll y = to[i], z = val[i];
if (vis[y])
continue;
dis[y] = dis[x] + z;
dfs(y);
}
}
int main()
{
IOS;
cin >> n >> k;
memset(head, -1, sizeof(head));
for (int i = 1; i < n; i++) //
{
int x, y, z;
cin >> x >> y >> z;
sum += z;
add(x, y, z);
add(y, x, z);
}
if (k >= 2)
{
cout << sum << endl;//nm伞兵
return 0;
}
memset(dis, 0, sizeof(dis));
memset(vis, 0, sizeof(vis));
dfs(1);
ll tmp = 0, p = 0;//caonm伞兵
for (int i = 1; i <= n; i++)
{
if (dis[i] > tmp)
tmp = dis[i], p = i;
}
// cout << p << endl;
memset(dis, 0, sizeof(dis));
memset(vis, 0, sizeof(vis));
dfs(p);
for (int i = 1; i <= n; i++)
res = max(dis[i], res);
cout << res << endl;
return 0;
}