标签:
DFS水题。题意说明了这是一颗树,那么只要按照根节点DFS下去就好了,DFS的时候记录一下当前在哪个结点,还有父节点是谁,就AC了!
#include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<algorithm> using namespace std; const int maxn = 100000 + 10; vector<int>ljb[maxn]; int anss[maxn], flag[maxn]; int n, s, u, v; void dfs(int noww, int father) { int i; anss[noww] = father; for (i = 0; i < ljb[noww].size(); i++) { if (flag[ljb[noww][i]] == 0) { flag[ljb[noww][i]] = 1; dfs(ljb[noww][i], noww); } } } int main() { int T; scanf("%d", &T); while (T--) { int i; scanf("%d%d", &n, &s); for (i = 0; i <= n; i++) ljb[i].clear(); memset(flag, 0, sizeof(flag)); for (i = 1; i <= n - 1; i++) { scanf("%d%d", &u, &v); ljb[u].push_back(v); ljb[v].push_back(u); } flag[s] = 1; dfs(s, -1); for (i = 1; i <= n; i++) { if (i < n) printf("%d ", anss[i]); else printf("%d\n", anss[i]); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/zufezzt/p/4592918.html