제출 #257515

#제출 시각아이디문제언어결과실행 시간메모리
257515BlagojceElection Campaign (JOI15_election_campaign)C++11
30 / 100
276 ms31252 KiB
#include <bits/stdc++.h> 
#define fr(i, n, m) for(int i = (n); i < (m); i ++)
#define pb push_back
#define st first
#define nd second
#define pq priority_queue
#define all(x) begin(x), end(x)
#include <time.h>
#include <cmath>
 
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;

const int i_inf = 1e9;
const ll inf = 1e17;
const ll mod = 1000000007;
const ld eps = 1e-13;
const ld pi  = 3.14159265359;
 
mt19937 _rand(time(NULL));
clock_t timer = clock();
const int mxn = 1e5;

int n, m;
vector<int> g[mxn];
int depth[mxn];
int sparse[mxn][20];
int sz[mxn];
int pos[mxn];
int temp;
void dfs(int u, int p){
	pos[u] = ++temp;
	sparse[u][0] = p;
	fr(i, 1, 20) sparse[u][i] = sparse[sparse[u][i-1]][i-1];
	sz[u] = 1;
	for(auto e : g[u]){
		if(e == p) continue;
		depth[e] = depth[u]+1;
		dfs(e, u);
		sz[u] += sz[e];
	}
}
int lca(int a, int b){
	int d = min(depth[a], depth[b]);
	for(int i = 19; i >= 0; i --){
		if(depth[a]-(1<<i) >= d) a = sparse[a][i];
		if(depth[b]-(1<<i) >= d) b = sparse[b][i];
	}
	if(a == b) return a;
	for(int i = 19; i >= 0; i --){
		if(sparse[a][i] != sparse[b][i]){
			a = sparse[a][i];
			b = sparse[b][i];
		}
	}
	return sparse[a][0];
}
int a[mxn], b[mxn], c[mxn];
vector<int> v[mxn];


int bit[2][mxn];
void update(int t, int k, int val){
	while(k < mxn){
		bit[t][k] += val;
		k += k&-k;
	}
}
int sum(int t, int k){
	int s = 0;
	while(k > 0){
		s += bit[t][k];
		k -= k&-k;
	}
	return s;
}

int dp[mxn];

void dfs2(int u, int p){
	int _sum = 0;
	for(auto e : g[u]){
		if(e == p) continue;
		dfs2(e, u);
		_sum += dp[e];
	}
	dp[u] = _sum;
	update(0, pos[u], _sum);
	update(0, pos[u]+sz[u], -_sum);
	
	for(auto e : v[u]){
		int tot = sum(0, pos[a[e]]) + sum(0, pos[b[e]]) - sum(0, pos[u]) - sum(1, pos[a[e]]) - sum(1, pos[b[e]]);
		tot += c[e];
		
		dp[u] = max(dp[u], tot);
	} 
	
	update(1, pos[u], dp[u]);
	update(1, pos[u]+sz[u], -dp[u]);
}

void solve(){
	cin >> n;
	fr(i, 0, n-1){
		int u, v;
		cin >> u >> v;
		--u, --v;
		g[u].pb(v);
		g[v].pb(u);
	}
	dfs(0, 0);
	cin >> m;
	fr(i, 0, m){
		cin >> a[i] >> b[i] >> c[i];
		--a[i], --b[i];
		int l = lca(a[i], b[i]);
		v[l].pb(i);
	}
	dfs2(0, 0);
	cout<<dp[0]<<endl;
}
 
int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	solve();
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...