[CF1790F] Timofey and Black-White Tree 题解
[CF1790F] Timofey and Black-White Tree 题解
题目描述
ZYH 有一棵
给定操作序列
多组数据,
思路
每次加入一个点暴力统计一遍答案,如果当前距离超过了答案就跳出。
这看着好像很暴力,似乎是平方的,但是其实是根号的,由于这个结论:
在一棵树上随机选择
证明:
对于一条链的情况,最坏情况是
个点隔 ,这种情况下的最小距离最大是 ,而对于一棵树,它是不比链的情况优的。
所以对于前
// Problem: Timofey and Black-White Tree
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF1790F
// Memory Limit: 250 MB
// Time Limit: 4000 ms
// Powered by CP Editor (https://cpeditor.org)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 2e5 + 10;
vector<int> g[N];
int q[N], dist[N], ans;
bool vis[N];
inline void bfs(int s) {
queue<int> q;
q.push(s);
dist[s] = 0;
while(q.size()) {
int t = q.front();
q.pop();
if(dist[t] >= ans) break;
for(auto v : g[t]) {
if(dist[v] <= dist[t] + 1) continue;
dist[v] = dist[t] + 1;
q.push(v);
}
}
}
int n;
inline void work() {
n = read();
q[0] = read();
for(int i = 1; i <= n; i ++) g[i].clear();
memset(dist, 0x3f, n + 1 << 2);
for(int i = 1; i < n; i ++) q[i] = read();
for(int i = 1, a, b; i < n; i ++) {
a = read(), b = read();
g[a].push_back(b), g[b].push_back(a);
}
ans = n + 1;
bfs(q[0]);
for(int i = 1; i < n; i ++) ans = min(ans, dist[q[i]]), bfs(q[i]), write(ans), putchar(' ');
puts("");
return ;
}
int main() {
int T = read();
while(T --) work();
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!