http://acm.nyist.net/JudgeOnline/problem.php?pid=20
1 #include<iostream>
2 #include<cstdio>
3 #include<queue>
4 #include<malloc.h>
5 #include<string.h>
6 using namespace std;
7 typedef struct city
8 {
9 int v;
10 //int fa;
11 struct city *next;
12 }City;
13 int n;
14 int fa[100005];
15 int vis[100005];
16 City c[100005];
17 queue<City> q;
18 void addarcs(int cfrom, int cto) //建立邻接表
19 {
20 City *p;
21 p = (City *)malloc(sizeof(City));
22 p -> v = cto;
23 //p -> fa = cfrom;
24 p -> next = c[cfrom].next;
25 c[cfrom].next = p;
26 }
27 void destroy(City *p) //递归释放空间
28 {
29 if(p == NULL)
30 return;
31 destroy(p -> next);
32 }
33 int main()
34 {
35 int start, i, tcases, a, b;
36 City *link;
37 scanf("%d", &tcases);
38 while(tcases--)
39 {
40 scanf("%d %d", &n, &start);
41 for(i = 1; i <= n; i++) //初始化
42 {
43 c[i].v = i;
44 //c[i].fa = 0;
45 c[i].next = NULL;
46 }
47 memset(vis, 0, sizeof(vis));
48 for(i = 0; i < n-1; i++)
49 {
50 scanf("%d%d", &a, &b);
51 addarcs(a, b);
52 addarcs(b, a);
53 }
54 fa[start] = -1; //bfs
55 vis[start] = 1;
56 q.push(c[start]);
57 while(!q.empty())
58 {
59 City p = q.front();
60 q.pop();
61 link = p.next;
62 while(link != NULL)
63 {
64 if(!vis[link -> v])
65 {
66 fa[link -> v] = p.v;
67 vis[link -> v] = 1;
68 q.push(c[link -> v]);
69 }
70 link = link -> next;
71 }
72 }
73 for(i = 1; i <= n; i++)
74 {
75 printf("%d", fa[i]);
76 if(i != n)
77 printf(" ");
78 }
79 putchar(10);
80 while(!q.empty()) //对bfs后的处理
81 q.pop();
82 for(i = 1; i <= n; i++)
83 destroy(&c[i]);
84 }
85 return 0;
86 }
今天又看到这道题,突然想起来刚看的无根树转化为有根树,又把这题做了一遍,结果时间又长了。。。这次是用vector<>存储的图,因此存储比较方便,但每次使用后要清空。。。如果上边的bfs也用vector存储的话,可能会快点吧。。。神马是无根树转化为有根树?我的理解是本来是一个无向连通并且无回路的图(也就是一颗树,只不过没有确定根),现在给树定一个根,让原来无序的图分层,表达能力不强,原谅我。。。vector挺好用的,没数据的时候不占空间,很方便。。。
1 #include<iostream>
2 #include<cstdio>
3 #include<vector>
4 #include<cstring>
5 using namespace std;
6
7 int N, root;
8 vector<int> G[100005];
9 int p[100005];
10
11 void dfs(int u, int fa)
12 {
13 int i, v;
14 int d = G[u].size();
15 for(i = 0; i < d; i++)
16 {
17 v = G[u][i];
18 if(v != fa)
19 {
20 p[v] = u;
21 dfs(v, u);
22 }
23 }
24 }
25
26 int main()
27 {
28 int ncases, u, v, i;
29 scanf("%d", &ncases);
30 while(ncases--)
31 {
32 scanf("%d%d", &N, &root);
33 for(i = 1; i < N; i++)
34 {
35 scanf("%d%d", &u, &v);
36 G[u].push_back(v);
37 G[v].push_back(u);
38 }
39 memset(p, 0, sizeof(p));
40 p[root] = -1;
41 dfs(root, -1);
42 for(i = 1; i <= N; i++)
43 {
44 printf("%d", p[i]);
45 if(i != N)
46 putchar(' ');
47 }
48 putchar(10);
49 for(i = 1; i <= N; i++)
50 {
51 if(G[i].size() != 0)
52 G[i].clear();
53 }
54 }
55 }