C. Fools and Roads(树上差分板子题)

//https://codeforces.com/problemset/problem/191/C
#include<bits/stdc++.h>
#include<unordered_map>
#include<array>
#define ll long long
#define ull unsigned long long
#define all(a) a.begin(),a.end()
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;

const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-4;
const ll mod = 998244353;
const int N = 1e5 + 50;

int n, val[N], ans[N];
vector<pair<int, int>> g[N];

struct LCA 
{
	int tot, fa[N], dep[N], sz[N], hson[N], top[N], dfn[N], rnk[N];
	void dfs1(int x, int father, int d)
	{
		dep[x] = d;
		hson[x] = -1;
		sz[x] = 1;
		for (auto [to, w] : g[x])
		{
			if (to == father)
				continue;
			fa[to] = x;
			dfs1(to, x, d + 1);
			sz[x] += sz[to];
			if (hson[x] == -1 || sz[to] > sz[hson[x]])
				hson[x] = to;
		}
	}

	void dfs2(int x, int t)
	{
		top[x] = t;//所在重链的最高点t
		dfn[x] = ++tot;
		rnk[tot] = x;
		if (hson[x] == -1)
			return;
		dfs2(hson[x], t);
		for (auto [to, w] : g[x])
		{
			if (to == fa[x] || to == hson[x])
				continue;
			dfs2(to, to);
		}
	}
	int lca(int x, int y)
	{
		int fx = top[x], fy = top[y];
		while (fx != fy)
		{
			if (dep[fx] > dep[fy])
			{
				x = fa[fx];
				fx = top[x];
			}
			else
			{
				y = fa[fy];
				fy = top[y];
			}
		}
		if (dep[x] > dep[y])
			return y;
		else
			return x;
	}
}L;

void dfs(int x, int fa)
{
	for (auto [to, id] : g[x])
	{
		if (to == fa)
			continue;
		dfs(to, x);
		ans[id] += val[to];
		val[x] += val[to];
	}
}

void solve()
{
	cin >> n;
	for (int i = 1, u, v; i < n; i++)
	{
		cin >> u >> v;
		g[u].push_back({ v, i });
		g[v].push_back({ u, i });
	}
	L.dfs1(1, -1, 0);
	L.dfs2(1, 1);

	int k;
	cin >> k;
	for (int i = 1, u, v; i <= k; i++)
	{
		cin >> u >> v;
		val[u]++;
		val[v]++;
		val[L.lca(u, v)] -= 2;
	}

	dfs(1, -1);
	for (int i = 1; i < n; i++)
		cout << ans[i] << ' ';
}

signed main()
{
	IOS;
	int t = 1;
	//cin >> t;
	while (t--)
		solve();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值