啊啊,最后一篇了,已经零点多了,我还打算写一段第一次打工赚钱做家教的感想呢……
接下来有时间做决赛题,感觉也不是很难吼?
题目链接:http://acm.uestc.edu.cn/#/problem/show/32
很简单的题目,比较一棵有根树两个节点哪个高度。
同样,用了一行广搜。不要问我为什么叫一行广搜,不要让我压代码压得不成样子,编程可是一种艺术……
也许我应该规范一下比如const变量的命名?
#include <cstdio>
#include <cstring>
using namespace std;
const int maxN = 100005;
int N, M;
int g[maxN], to[maxN], next[maxN], e;
int root, father[maxN];
int queue[maxN], head, tail, depth[maxN];
int nextInt() {
char c; while ((c = getchar()) < ‘0‘ || c > ‘9‘); int r = c - ‘0‘;
while ((c = getchar()) >= ‘0‘ && c <= ‘9‘) (r *= 10) += c - ‘0‘;
return r;
}
void addEdge(int u, int v) {
next[e] = g[u]; to[e] = v; g[u] = e++;
}
void bfs(int root) {
memset(depth, 0, sizeof depth);
for (queue[head = tail = 0] = root; head <= tail; ++head)
for (int e = g[queue[head]], child = to[e]; ~e; child = to[e = next[e]])
if (child != father[queue[head]]) depth[child] = depth[queue[head]] + 1, queue[++tail] = child;
}
int main() {
while ((N = nextInt()) && (M = nextInt())) {
memset(g, -1, sizeof g); e = 0;
memset(father, 0, sizeof father);
for (int i = 1; i < N; ++i) {
int A = nextInt(), B = nextInt();
addEdge(A, B); father[B] = A;
}
for (int i = 1; i <= N; ++i)
if (!father[i]) {
root = i; break;
}
bfs(root);
while (M--) {
int X = nextInt(), Y = nextInt();
if (depth[X] <= depth[Y]) puts("lxh"); else puts("pfz");
}
}
return 0;
}
OK,我写一遍真正的一行广搜。其实上面那个bfs只是把变量名变长了以及加了空格和换行而已,一些变量名稍微有变化,可以对照着上面的bfs函数看。
for(q[h=t=0]=rt;h<=t;++h)for(int e=g[q[h]];~e;e=nxt[e])if(to[e]!=p[q[h]])d[to[e]]=d[q[h]]+1,q[++t]=to[e];
杀了我吧,这段代码太丑了。
时间: 2024-10-19 05:07:01