Submission #423448

#TimeUsernameProblemLanguageResultExecution timeMemory
423448codebuster_10Race (IOI11_race)C++17
100 / 100
598 ms80796 KiB
#include <bits/stdc++.h>

using namespace std ;


#define f(i,a,b) for(int i=int(a);i<int(b);++i)

#define pr pair
#define ar array
#define fr first
#define sc second
#define vt vector
#define pb push_back
#define eb emplace_back
#define LB lower_bound  
#define UB upper_bound
#define PQ priority_queue

#define sz(x) ((int)(x).size())
#define all(a) (a).begin(),(a).end()
#define allr(a) (a).rbegin(),(a).rend()
#define mem(a,b) memset(a, b, sizeof(a))

template<class T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }

























int best_path(int N, int K, int H[][2], int L[])	{
	vt<ar<int,2>> g[N];
	f(i,0,N-1){
		int u = H[i][0], v = H[i][1], w = L[i];
		g[u].pb({v,w});
		g[v].pb({u,w});
	}
	
	
	int ans = N;
	
	map<int,int> dp[N];
	vt<int> ew(N), el(N);	/* current dp[i] is actually {a + extra_weight, b + extra_length} */
	
	function<void(int,int)> small_to_large_merging = [&](int i,int p){
		dp[i][0] = ew[i] = el[i] = 0;
		for(auto [j,w] : g[i]) if(j != p){
			small_to_large_merging(j,i);
			if(sz(dp[i]) > sz(dp[j])){
				
				
				// update ans.
				for(auto [w_j, l_j] : dp[j]){
					int actual_w = w_j + ew[j] + w;
					int actual_l = l_j + el[j] + 1;
					int need_w = K - actual_w;
					int put_i = need_w - ew[i];
					if(dp[i].count(put_i)){
						ckmin(ans,dp[i][put_i] + el[i] + actual_l);
					}
				}
				
				// update dp[i].
				for(auto [w_j, l_j] : dp[j]){
					int actual_w = w_j + ew[j] + w;
					int actual_l = l_j + el[j] + 1;
					int put_i = actual_w - ew[i];
					int put_l = actual_l - el[i];
					if(dp[i].count(put_i)){
						ckmin(dp[i][put_i], put_l);
					}else{
						dp[i][put_i] = put_l;
					}
				}
				
				dp[j].clear();
			}else{
				
				// update ans.
				for(auto [w_i,l_i] : dp[i]){
					int actual_w = w_i + ew[i] + w;
					int actual_l = l_i + el[i] + 1;
					int need_w = K - actual_w;
					int put_j = need_w - ew[j];
					if(dp[j].count(put_j)){
						ckmin(ans,dp[j][put_j] + el[j] + actual_l);
					}
				}
				
				//update dp[j].
				el[j] += 1;
				ew[j] += w;
				for(auto [w_i,l_i] : dp[i]){
					int actual_w = w_i + ew[i];
					int actual_l = l_i + el[i];
					int put_j = actual_w - ew[j];
					int put_l = actual_l - el[j];
					if(dp[j].count(put_j)){
						ckmin(dp[j][put_j],put_l);
					}else{
						dp[j][put_j] = put_l;
					}
				}
				
				// swap
				dp[i].swap(dp[j]);
				dp[j].clear();
				ew[i] = ew[j];
				el[i] = el[j];
	
			}
		}
	};
	small_to_large_merging(0,0);
	if(ans == N) ans = -1;
	return ans;
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...