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>
typedef int ll;
typedef long double ld;
#define pb push_back
#define pii pair < int, int >
#define F first
#define S second
//#define int long long int
#define sync ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#pragma GCC optimize ("Ofast")
#pragma GCC optimize ("unroll-loops")
#define endl '\n'
using namespace std;
const int N=10002;
vector <pii> g[N];
ll vis[N];
ll ans=0;
ll dp[N][2];
void dfs(ll v,ll p,ll w){
vector <pii> a;
for (auto u : g[v]){
if (u.F==p) continue;
dfs(u.F,v,u.S);
dp[v][1]+=dp[u.F][0];
a.pb({dp[u.F][1]+u.S-dp[u.F][0],dp[u.F][0]});
}
sort(a.begin(),a.end());
reverse(a.begin(),a.end());
if (p!=-1 && a.size()){
ll cnt=0;
for (int i=0;i<a.size();i++){
cnt+=a[i].S;
}
cnt+=a[0].F+w;
dp[v][0]=max(dp[v][1],cnt);
}
}
int32_t main(){
sync;
ll n;
cin >> n;
for (int i=0;i<n-1;i++){
ll u,v,w;
cin >> u >> v >> w;
g[u].pb({v,w});
g[v].pb({u,w});
}
for (int i=1;i<=n;i++){
vector <pii> a;
for (auto q : g[i]){
ll u=q.F;
if (g[u].size()==1) a.pb({q.S,u});
}
sort(a.begin(),a.end());
for (int j=1;j<a.size();j++){
vis[a[j].S]=1;
}
}
ll ma=0;
ll q=1e9,z=1;
for (int i=1;i<=n;i++){
if (g[i].size()!=1) continue;
if (g[i][0].S<q){
q=g[i][0].S;
z=i;
}
}
for (int i=1;i<=n;i++){
if (g[i].size()!=1 && vis[i]!=1) continue;
memset(vis,0,sizeof vis);
memset(dp,0,sizeof dp);
ans=0;
dfs(i,-1,0);
ma=max(ma,dp[i][1]);
// cout << i << " " << dp[i][1] << endl;
}
cout << ma << endl;
}
/*
10
4 10 2
1 2 21
1 3 13
6 7 1
7 9 5
2 4 3
2 5 8
1 6 55
6 8 34
*/
/*
6
1 2 20
2 3 20
3 4
10
3 5 10
3 6 10
*/
Compilation message (stderr)
beads.cpp: In function 'void dfs(ll, ll, ll)':
beads.cpp:31:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int i=0;i<a.size();i++){
~^~~~~~~~~
beads.cpp: In function 'int32_t main()':
beads.cpp:55:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int j=1;j<a.size();j++){
~^~~~~~~~~
beads.cpp:60:14: warning: variable 'z' set but not used [-Wunused-but-set-variable]
ll q=1e9,z=1;
^
# | 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... |