无根树转为有根数(图论) By ACReaper
给结点分别编号,输入这个无向图的的边,它只有n - 1条边,所以本质上也是树,但是我们还没有确定树的root的结点,下面我们来构造一颗树。
我们用邻接矩阵来存下整个图,这里用C++里的vector这中数据结构,它是可以变长的,所以存下之后,空间复杂度就不是n * n了,而是n。
给出一组数据:
一共8个结点,从0----7编号。我们假定以1为根结点构建树。
边数据如下:
0 10 2
0 3
1 4
1 5
5 6
5 7
在邻接矩阵中,他表示为:
0| 1 2 3
1| 0 4 5
2|0
3|0
4|1
5|6 7
6|5
7|5
下面给出代码实现:为了验证正确性,我让它以先序遍历输出了
#include <iostream.h> #include <vector.h> const int maxn = 1000; vector<int> G[maxn]; int p[maxn]; int n; void read_tree(){ int u,v; scanf("%d",&n); for(int i = 1; i <= n - 1; i++){ scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } } void dfs(int u,int fa){ int d = G[u].size(); printf("%d ",u); for(int i = 0; i < d; i++){ int v = G[u][i]; if(v != fa){ dfs(v,p[v] = u); } } } int main(){ int root; while(scanf("%d",&root) != EOF){ read_tree(); p[root] = -1; dfs(root,-1); } return 0; }
输出结果为:1 0 2 3 4 5 6 7
结果正确。
2013 04 22 By ACReaper