제출 #201070

#제출 시각아이디문제언어결과실행 시간메모리
201070mraronPutovanje (COCI20_putovanje)C++14
110 / 110
220 ms43296 KiB
#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<cassert>
#include<cassert>
#include<unordered_map>
#include<unordered_set>
#include<functional>
#include<queue>
#include<stack>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<sstream>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<numeric>
#include<random>
#include<chrono>
#include<bitset>
using namespace std;

#define all(x) (x).begin(), (x).end()
#define pb push_back
#define xx first
#define yy second
#define sz(x) (int)(x).size()
#define gc getchar
#define IO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mp make_pair

#ifndef ONLINE_JUDGE
#  define LOG(x) (cerr << #x << " = " << (x) << endl)
#else
#  define LOG(x) ((void)0)
#endif

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

const double PI=3.1415926535897932384626433832795;
const ll INF = 1LL<<62;
const ll MINF = -1LL<<62;

template<typename T> T getint() {
	T val=0;
	char c;
	
	bool neg=false;
	while((c=gc()) && !(c>='0' && c<='9')) {
		neg|=c=='-';
	}

	do {
		val=(val*10)+c-'0';
	} while((c=gc()) && (c>='0' && c<='9'));

	return val*(neg?-1:1);
}

//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); uniform_int_distribution<int>(0, n-1)(rng)
int n;
vector<pair<int,int>> adj[200001];
set<int> lst[200001];
int st[200001];
ll c[2][200001];
int par[200001], par_e[200001];
ll cnt[200001];

ll solve(int x) {
	st[x]=1;
	ll cost=0;
	for(auto i:adj[x]) {
		if(!st[i.xx]) {
			par[i.xx]=x;
			par_e[i.xx]=i.yy;
			cost+=solve(i.xx);
		}
	}
	
	if(!cost) {
		lst[x].insert(x);
		return cnt[par_e[x]]=2;
	}
	
	ll mx=adj[x][0].xx;
	for(auto i:adj[x]) {
		if(par[i.xx]==x) {
			if(lst[i.xx].size()>lst[mx].size()) mx=i.xx;
		}
	}
	
	auto berak=[&](int j) {
		auto it=lst[x].insert(j).xx;
		int elotte=(it!=lst[x].begin()&&*prev(it)==j-1);
		int utana=(it!=prev(lst[x].end())&&*next(it)==j+1);
		if(!elotte &&  !utana) {
			cost+=2;
		}else if(elotte+utana==1) {
				
		}else {
			cost-=2;
		}
	};	
	
	lst[x].swap(lst[mx]);
	//cerr<<cnt[mx]<<"\n";
	cost=cnt[par_e[mx]];
	berak(x);
	for(auto i:adj[x]) {
		if(par[i.xx]==x) {
			for(auto j:lst[i.xx]) {
				berak(j);
			}
		} 
	}
	
	/*cerr<<x<<": ";
	for(auto i:lst[x]) cerr<<i<<" ";
	cerr<<"\n";*/
	
	return cnt[par_e[x]]=cost;
}


int main() {
	IO;
	cin>>n;
	for(int i=1;i<n;++i) {
		int a,b;
		cin>>a>>b>>c[0][i]>>c[1][i];
		adj[a].push_back({b,i});
		adj[b].push_back({a,i});
	}

	solve(1);

	int akt=n;
	while(akt!=1) {
		cnt[par_e[akt]]--;
		akt=par[akt];
	}

	ll ans=0;
	for(int i=1;i<n;++i) {
		//cerr<<i<<" "<<cnt[i]<<"\n";
		ans+=min(c[0][i]*cnt[i], c[1][i]);
	}
	
	cout<<ans<<"\n";

	

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