結果
問題 | No.1488 Max Score of the Tree |
ユーザー |
![]() |
提出日時 | 2021-04-23 22:46:13 |
言語 | Rust (1.83.0 + proconio) |
結果 |
AC
|
実行時間 | 16 ms / 2,000 ms |
コード長 | 2,186 bytes |
コンパイル時間 | 13,590 ms |
コンパイル使用メモリ | 401,524 KB |
実行使用メモリ | 6,944 KB |
最終ジャッジ日時 | 2024-07-04 08:28:44 |
合計ジャッジ時間 | 13,976 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
#![allow(unused_imports)]use std::cmp::*;use std::collections::*;use std::io::Write;use std::ops::Bound::*;#[allow(unused_macros)]macro_rules! debug {($($e:expr),*) => {#[cfg(debug_assertions)]$({let (e, mut err) = (stringify!($e), std::io::stderr());writeln!(err, "{} = {:?}", e, $e).unwrap()})*};}fn main() {let v = read_vec::<usize>();let (n, k) = (v[0], v[1]);let mut edges = vec![vec![]; n];let mut edges_list = HashMap::new();let mut weights = vec![];for i in 0..n - 1 {let v = read_vec::<usize>();let (a, b, c) = (v[0] - 1, v[1] - 1, v[2] as i64);edges[a].push(b);edges[b].push(a);edges_list.insert((a, b), i);edges_list.insert((b, a), i);weights.push(c);}let mut accum = vec![0; n - 1];dfs(0, 0, &edges, &edges_list, &mut accum);let mut dp = vec![-1; k + 1];dp[0] = 0;for i in 0..n - 1 {for prev in (0..k).rev() {let next = prev + weights[i] as usize;if next > k || dp[prev] == -1 {continue;}dp[next] = max(dp[next], dp[prev] + weights[i] * accum[i]);}}let ans = dp.iter().max().unwrap() + (0..n - 1).map(|i| weights[i] * accum[i]).sum::<i64>();println!("{}", ans);}fn dfs(cur: usize,parent: usize,edges: &Vec<Vec<usize>>,edges_list: &HashMap<(usize, usize), usize>,accum: &mut Vec<i64>,) -> i64 {if edges[cur].iter().filter(|&&x| x != parent).count() == 0 {return 1;}let mut ret = 0;for &to in edges[cur].iter().filter(|&&x| x != parent) {let edge_index = edges_list[&(cur, to)];accum[edge_index] = dfs(to, cur, edges, edges_list, accum);ret += accum[edge_index];}ret}fn read<T: std::str::FromStr>() -> T {let mut s = String::new();std::io::stdin().read_line(&mut s).ok();s.trim().parse().ok().unwrap()}fn read_vec<T: std::str::FromStr>() -> Vec<T> {read::<String>().split_whitespace().map(|e| e.parse().ok().unwrap()).collect()}