Submission #254832

#TimeUsernameProblemLanguageResultExecution timeMemory
254832errorgornFireworks (APIO16_fireworks)C++14
100 / 100
301 ms73336 KiB
//雪花飄飄北風嘯嘯
//天地一片蒼茫
 
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se second
#define endl '\n'
#define debug(x) cout << #x << " is " << x << endl;
 
#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))
#define all(x) (x).begin(),(x).end()
#define sz(x) (int)(x).size()
 
ll MAX(ll a){return a;}
ll MIN(ll a){return a;}
template<typename... Args>
ll MAX(ll a,Args... args){return max(a,MAX(args...));}
template<typename... Args>
ll MIN(ll a,Args... args){return min(a,MIN(args...));}
 
#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>
 
mt19937 rng(chrono::system_clock::now().time_since_epoch().count());
 
int n,m;
vector<int> al[300005];
ll d[300005];
 
ll w[300005];
priority_queue<ll> pq[300005];
 
void dfs(int i){
	if (i>n){
		pq[i].push(0);
		pq[i].push(0);
	}
	else{
		vector<ll> tops;
		
		int grad=-1;
		for (auto &it:al[i]){
			dfs(it);
			d[i]+=d[it];
			grad++;
			
			tops.push_back(pq[it].top());
			if (pq[i].empty()) swap(pq[i],pq[it]);
			else{
				if (sz(pq[i])<sz(pq[it])) swap(pq[i],pq[it]);
				
				while (!pq[it].empty()){
					pq[i].push(pq[it].top());
					pq[it].pop();
				}
			}
		}
		
		for (auto &it:tops) d[i]+=pq[i].top()-it;
		while (grad){
			ll temp=pq[i].top();
			pq[i].pop();
			d[i]-=grad*(temp-pq[i].top());
			grad--;
		}
	}
	
	ll t1,t2;
	t1=pq[i].top(),pq[i].pop();
	t2=pq[i].top(),pq[i].pop();
	pq[i].push(t1+w[i]);
	pq[i].push(t2+w[i]);
}
 
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	
	cin>>n>>m;
	
	int a,b;
	rep(x,2,n+m+1){
		cin>>a>>b;
		al[a].push_back(x);
		w[x]=b;
	}
	
	dfs(1);
	cout<<d[1]<<endl;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...