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>
using namespace std;
using ll = long long;
using str = string;
using ld = long double;
using T = tuple<ll, ll, ll>;
#define int long long
#define Base 31
#define sz(a) (int)a.size()
#define FOR(i, a, b) for ( int i = a ; i <= b ; i++ )
#define FORD(i, a, b) for (int i = a; i >= b; i --)
#define REP(i, n) for ( int i = 0 ; i < n ; ++i )
#define REPD(i, n) for ( int i = n - 1 ; ~(--i) ; )
#define all(x) x.begin() , x.end()
#define pii pair<int , int>
#define fi first
#define se second
#define Lg(x) 31 - __builtin_clz(x)
constexpr ll LINF = (1ll << 62);
constexpr int INF = (1ll << 30);
constexpr int MAX = 2e5 + 5;
constexpr int Mod = 1e9 + 7;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
void setupIO(){
#define name "Whisper"
//Phu Trong from Nguyen Tat Thanh High School for gifted student
srand(time(NULL));
cin.tie(nullptr)->sync_with_stdio(false); cout.tie(nullptr);
// freopen(name".inp", "r", stdin);
// freopen(name".out", "w", stdout);
cout << fixed << setprecision(10);
}
int n;
vector<T> adj[MAX];
const int Log = 20;
int up[MAX][Log], dep[MAX], f[MAX];
int ans = 0;
//using f(i) as the number we come to the ith city with minimize cost
void dfs(int u, int p){
for (auto&[v, _, __] : adj[u]) if(v ^ p){
dep[v] = dep[u] + 1;
up[v][0] = u;
for (int i = 1 ; i < Log ; i++){
up[v][i] = up[up[v][i - 1]][i - 1];
}
dfs(v, u);
}
}
void Lca(int u, int v){
f[u]++, f[v]++;
if (dep[u] < dep[v]) swap(u, v);
int dis = dep[u] - dep[v];
for (; dis > 0; dis ^= (dis & (-dis))){
int i = __builtin_ctz(dis & (-dis));
u = up[u][i];
}
if (u == v){
f[u] -= 2;
return;
}
int k = Lg(dep[v]);
for (int i = k ; i >= 0 ; i--){
if (up[u][i] != up[v][i]){
u = up[u][i];
v = up[v][i];
}
}
f[up[u][0]] -= 2;
}
void cal(int u, int p){
for (auto&[v, c1, c2] : adj[u]) if(v ^ p){
cal(v, u);
f[u] += f[v];
ans += min(f[v] * c1, c2);
}
}
void Whisper(){
cin >> n;
for (int i = 1 ; i < n ; i++){
int u, v, c1, c2; cin >> u >> v >> c1 >> c2;
adj[u].push_back({v, c1, c2});
adj[v].push_back({u, c1, c2});
}
dfs(1, 0);
for(int i = 1 ; i < n ; i++){
Lca(i, i + 1);
}
cal(1, 0);
cout << ans;
}
signed main(){
setupIO();
int Test = 1;
// cin >> Test;
for ( int i = 1 ; i <= Test ; i++ ){
Whisper();
if (i < Test) cout << '\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |