Example

Input

3 2
1 2 1
2 3 2
1 10 100


Output

320
#include <bits/stdc++.h>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<string> vs;
typedef vector<P> vp;
typedef vector<vp> vvp;
typedef vector<pll> vpll;
typedef pair<int,P> pip;
typedef vector<pip> vip;
const int inf=1<<30;
const ll INF=1ll<<60;
const double pi=acos(-1);
const double eps=1e-8;
const ll mod=1e9+7;
const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};

int n,m;
vvp g;
vl a;
vp b;
vi par,used;

void dfs(int v,int pre){
	par[v]=pre;
	b[v]={0,v};
	for(auto p:g[v]){
		int u=p.first;
		if(u!=pre){
			dfs(u,v);
			b[v]=max(b[v],{b[u].first+p.second,b[u].second});
		}
	}
}

int main(){
	cin>>n>>m;
	g=vvp(n);
	for(int i=1;i<n;i++){
		int u,v,w;
		cin>>u>>v>>w;
		u--;v--;
		g[u].push_back({v,w});
		g[v].push_back({u,w});
	}
	for(int i=0;i<n;i++){
		ll x;
		cin>>x;
		b=vp(n);
		par=used=vi(n);
		dfs(i,-1);
		priority_queue<P> q;
		q.push(b[i]);
		while(!q.empty()){
			P p=q.top();q.pop();
			int v=p.second;
			if(used[v]) continue;
			a.push_back(x*p.first);
			used[v]++;
			v=par[v];
			while(v>=0&&!used[v]){
				for(auto pp:g[v]){
					int u=pp.first,c=pp.second;
					if(u!=par[v]){
						int w=b[u].second;
						if(!used[w]) q.push({b[u].first+c,w});
					}
				}
				used[v]++;
				v=par[v];
			}
		}
	}
	sort(a.rbegin(),a.rend());
	int N=a.size();
	ll res=0;
	for(int i=0;i<min(N,m);i++) res+=a[i];
	cout<<res<<endl;
}
