제출 #299500

#제출 시각아이디문제언어결과실행 시간메모리
299500shivensinha4Putovanje (COCI20_putovanje)C++17
110 / 110
279 ms17720 KiB
#include <bits/stdc++.h> 
using namespace std; 
#define for_(i, s, e) for (int i = s; i < (int) e; i++)
#define for__(i, s, e) for (ll i = s; i < e; i++)
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
#define endl '\n'

vi ct;

class SegmentTree {
	private:
		vi tree; int n;
		int bound = 0;
		
		void update(int i, int j, int val, int l, int r, int p) {
			if (l > j or r < i) return;
			if (l >= i and r <= j) {
				tree[p] += val;
				return;
			}
			
			int mid = (l + r) / 2;
			int c1 = 2*p+1, c2 = 2*p+2;
			update(i, j, val, l, mid, c1); update(i, j, val, mid+1, r, c2);
		}
		
		void ans(int l, int r, int p, int inc) {
			if (l == r) {
				ct[l] = tree[p]+inc;
				return;
			}
			
			inc += tree[p];
			int mid = (l + r) / 2;
			int c1 = 2*p+1, c2 = 2*p+2;
			ans(l, mid, c1, inc); ans(mid+1, r, c2, inc);
			
		}
	public: 
		void build(int N) {
			n = N;
			tree.resize(4*n, 0);
		}
		
		void update(int i, int j, int val) {
			update(i, j, val, 0, n-1, 0);
		}
		
		void ans() {
			ans(0, n-1, 0, 0);
		}
};


int n, pt = 0;
vector<vector<ii>> adj;
vector<ll> c1, c2;
vi heavy, head, pos, depth, parent, node;
SegmentTree tree;

int dfs(int p) {
	int sz = 1, maxChildSz = 0;
	for (auto i: adj[p]) if (i.first != parent[p]) {
		int v = i.first;
		node[i.second] = v;
		parent[v] = p;
		depth[v] = depth[p]+1;
		int s = dfs(v);
		sz += s;
		if (s > maxChildSz) {
			maxChildSz = s;
			heavy[p] = v;
		}
	}
	return sz;
}

void decompose(int p, int h) {
	head[p] = h; pos[p] = pt++;
	if (heavy[p] != -1) decompose(heavy[p], h);
	for (auto i: adj[p]) if (i.first != parent[p] and i.first != heavy[p]) decompose(i.first, i.first);
}

void query(int a, int b) {
	for (; head[a] != head[b]; b = parent[head[b]]) {
		if (depth[head[a]] > depth[head[b]]) swap(a, b);
		tree.update(pos[head[b]], pos[b], 1);
    }
    if (depth[a] > depth[b]) swap(a, b);
    tree.update(pos[a]+1, pos[b], 1);
}

int main() {
	#ifdef shiven
	freopen("test.in", "r", stdin);
	#endif
	
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	
	cin >> n;
	adj.resize(n); ct.resize(n); c1.resize(n-1); c2.resize(n-1); parent.resize(n); heavy.resize(n, -1); head.resize(n); pos.resize(n); depth.resize(n); node.resize(n-1);
	tree.build(n);
	
	for_(i, 0, n-1) {
		int a, b; cin >> a >> b >> c1[i] >> c2[i];
		a -= 1; b -= 1;
		adj[a].push_back({b, i});
		adj[b].push_back({a, i});
	}
	
	dfs(0);
	decompose(0, 0);
	for_(i, 0, n-1) query(i, i+1);
	tree.ans();
	ll ans = 0;
	for_(i, 0, n-1) {
		ll a = c1[i], b = c2[i], c = ct[pos[node[i]]];
		ans += min(c*a, b); 
	}
	
	cout << ans << endl;

	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...