题解:P10731 [NOISG 2023 Qualification] Network
Restatement
首先可以发现:第
那么我们的目标就转化为让每条路径
Analysis
我们可以递归地逐个节点考虑贪心。对于一个点
这时有
Case 1
若
对于这种情况的维护,可以考虑使用重链剖分套树状数组。每次选中一个点时单点加
Case 2
否则,若
Case 3
否则,选择
考虑下图。
其中路径分别为
如果在
下面来证明这个结论。设有
那么,不选
即,选择这些经过
这时
Solution
综合上述分析,可以得到解决这个问题的算法。
最开始初始化重链剖分。将路径 vector 或链式前向星实现。同时保存
实现一个递归函数,对于一个点,先递归处理其儿子。
然后访问每个挂到这个点上的路径
时间复杂度
Code
第
#include <iostream>
#include <utility>
#define MAXN 200003
#define LOGN 21
using namespace std;
template <int ESIZ>
struct Graph
{
pair<int, int> edges[ESIZ];
int cnt, head[MAXN];
void add_edge(const int &from, const int &to)
{
edges[++cnt] = {to, head[from]}, head[from] = cnt;
}
};
Graph<MAXN * 2 + 1> g;
Graph<MAXN> gqur;
int n, ansc, fa[MAXN], dep[MAXN], siz[MAXN], hson[MAXN], top[MAXN], dfn[MAXN], ans[MAXN];
pair<int, int> qur[MAXN][LOGN];
namespace BIT
{
int c[MAXN];
inline int lowbit(const int &x)
{
return x & -x;
}
inline void update(int pos)
{
while (pos <= n)
{
++c[pos];
pos += lowbit(pos);
}
}
inline int query(int pos)
{
int rv = 0;
while (pos)
{
rv += c[pos];
pos -= lowbit(pos);
}
return rv;
}
}
void dfs1(const int &u)
{
int f = fa[u], hcur = 0, hsiz = 0;
siz[u] = 1;
for (int i = g.head[u], to; i; i = g.edges[i].second)
{
to = g.edges[i].first;
if (to == f)
continue;
fa[to] = u, dep[to] = dep[u] + 1;
dfs1(to);
siz[u] += siz[to];
if (siz[to] > hsiz)
hsiz = siz[to], hcur = to;
}
hson[u] = hcur;
}
void dfs2(const int &u, const int &tp)
{
static int ts;
int f = fa[u], h = hson[u];
top[u] = tp, dfn[u] = ++ts;
if (h)
dfs2(h, tp);
for (int i = g.head[u], to; i; i = g.edges[i].second)
{
to = g.edges[i].first;
if (to == f || to == h)
continue;
dfs2(to, to);
}
}
inline int LCA(int u, int v, pair<int, int> *arr)
{
while (top[u] != top[v])
{
if (dep[top[u]] < dep[top[v]])
swap(u, v);
*++arr = {dfn[top[u]], dfn[u]};
u = fa[top[u]];
}
if (dep[u] > dep[v])
swap(u, v);
*++arr = {dfn[u], dfn[v]};
return u;
}
void dfs3(const int &u)
{
int f = fa[u];
for (int i = g.head[u], to; i; i = g.edges[i].second)
{
to = g.edges[i].first;
if (to == f)
continue;
dfs3(to);
}
bool flag;
for (int i = gqur.head[u], to; i; i = gqur.edges[i].second)
{
to = gqur.edges[i].first;
flag = true;
for (int p = 1; qur[to][p].first; ++p)
flag &= BIT::query(qur[to][p].first - 1) == BIT::query(qur[to][p].second);
if (flag)
{
BIT::update(dfn[u]);
ans[++ansc] = u;
break;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int m, u, v;
cin >> n >> m;
for (int i = 1; i < n; ++i)
cin >> u >> v, g.add_edge(u, v), g.add_edge(v, u);
dfs1(1), dfs2(1, 1);
for (int i = 1; i <= m; ++i)
cin >> u >> v, gqur.add_edge(LCA(u, v, qur[i]), i);
dfs3(1);
cout << ansc << '\n';
for (int i = 1; i <= ansc; ++i)
cout << ans[i] << ' ';
return 0;
}