一看就是lca的板子题
然而
(写这个的时候我忘了怎么写lca)
于是我就试着写暴力了
本以为会tle结果e了一次后居然a掉了
开心到起飞.嘿嘿嘿
但还是格式输出错误了一次而且在ce之前也de了一会儿(sdqxt太蒻了)
sd错误如下:
1. 边的编号和点的编号弄混了
2. 一开始直接写成i <= deep[x] – deep[y]
于是导致循环少了好几次
(这个问题我在博客了写了好多遍,可我还是错qwq..)
3. 但我真正提交的错误是, 被我写成'空格'了(纯是没在意这事啊)
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> using namespace std; int fa[10005],deep[10005],head[10005],nxt[10005],to[10005],cnt; bool vis[10005]; inline int read() { int sum = 0,p = 1; char ch = getchar(); while(ch < '0' || ch > '9') { if(ch == '-') p = -1; ch = getchar(); } while(ch >= '0' && ch <= '9') { (sum *= 10) += ch - '0'; ch = getchar(); } return sum * p; } void dfs(int o) { for(int i = head[o];i;i = nxt[i]) { deep[to[i]] = deep[o] + 1; dfs(to[i]); } } void add(int x,int y) { fa[y] = x; nxt[++cnt] = head[x]; head[x] = cnt; to[cnt] = y; } void llca(int x,int y) { if(deep[x] < deep[y])//始终让x为最深的 swap(x,y); int qwq = deep[x] - deep[y]; for(int i = 1;i <= qwq;i++) x = fa[x]; if(x == y) printf("%d ",y); else { while(x != y) { x = fa[x]; y = fa[y]; } printf("%d ",y); } } int main() { int t,n; t = read(); while(t--) { n = read(); cnt = 0; memset(fa,0,sizeof(fa)); memset(deep,0,sizeof(deep)); memset(head,0,sizeof(head)); memset(nxt,0,sizeof(nxt)); memset(vis,0,sizeof(vis)); memset(to,0,sizeof(to)); for(int i = 1;i < n;i++) { int a= read(),b = read(); vis[b] = true; add(a,b); } int c = read(),d = read(); for(int i = 1;i <= n;i++)//找根节点 if(!vis[i]) { deep[i] = 1; fa[i] = i; dfs(i); break; } llca(c,d); } return 0; }