This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
int n,k;
vector<ii> G[100005];
ll d[100005];
int p[100005][18];
int dep[100005];
int d1 = 0;
int d2 = 0;
int dp[100005];
int vis[19];
ll md = 0;
void dfs(int u){
for (auto v : G[u]){
if (v.fi == p[u][0]) continue;
d[v.fi] = d[u]+v.se;
dep[v.fi] = dep[u]+1;
p[v.fi][0] = u;
dp[v.fi] = v.se;
dfs(v.fi);
}
}
int lca(int a, int b){
if (dep[a] > dep[b]) swap(a,b);
int DD = dep[b] - dep[a];
for (int k = 0; k < 18; k++){
if (DD>>k&1){
b = p[b][k];
}
}
if (a == b) return a;
for (int k = 17; k >= 0; k--){
if (p[a][k] != -1 && p[a][k] != p[b][k]){
a = p[a][k];
b = p[b][k];
}
}
assert(p[a][0] == p[b][0]);
return p[a][0];
}
ll dist(int a, int b){
return d[a] + d[b] - 2*d[lca(a,b)];
}
int main(){
scanf("%d%d",&n,&k);
for (int i = 1 ; i < n; i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
G[a].push_back({b,c});
G[b].push_back({a,c});
}
memset(p,-1,sizeof(p));
p[1][0] = -1;
dfs(1);
for (int k = 1; k < 18; k++){
for (int i = 1; i <=n ;i ++ ){
if (p[i][k-1] != -1) p[i][k] = p[p[i][k-1]][k-1];
}
}
if (k == 1){
for (int i = 1; i <= n; i++){
if (d1 == 0 || d[d1] < d[i]) d1 = i;
}
for (int i = 1; i <= n; i++){
ll nd = dist(d1, i);
if (md < nd){
d2 = i;
md = nd;
}
}
for (int i = 1; i <= n; i++){
printf("%lld\n",max(dist(i,d1), dist(i,d2)));
}
}
else{
for (int i = 1; i <= n; i++){
d[i] = 0;
p[i][0] = -1;
dp[i] = 0;
dfs(i);
ll ans = 0;
for (int mask = 1; mask < (1<<n); mask++){
if (__builtin_popcount(mask) != k) continue;
memset(vis,0,sizeof(vis));
ll sm = 0;
for (int i = 1; i <= n; i++){
if (mask>>(i-1)&1){
int cur = i;
while (cur != -1 && !vis[cur]){
vis[cur] = true;
sm += dp[cur];
cur = p[cur][0];
}
}
}
ans = max(ans,sm);
}
printf("%lld\n",ans);
}
}
}
Compilation message (stderr)
Main.cpp: In function 'int main()':
Main.cpp:49:10: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
49 | scanf("%d%d",&n,&k);
| ~~~~~^~~~~~~~~~~~~~
Main.cpp:52:14: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
52 | scanf("%d%d%d",&a,&b,&c);
| ~~~~~^~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |