树的表示法

图论的题目难在建图

二叉树(基础)

并查集(有根树)

生成树(图论)

Trie树(字典树)

哈弗曼树(编码树)

二叉排序树(BST,平衡树,伸展树,动态树)

线段树(扩展)

树的表示:

1.”fa型”
in[i]==0找root

1
2
3
4
5
int fa[maxn];
int in[maxn];
int out[maxn];

加边: fa[v]=u; in[v]++;

2.”邻接表”

1
2
3
4
5
vector<int> V[maxn];

加边: V[u].push_back(v); in[v]++;
遍历: for (int i=0;i<V[u].size();i++)
V[u][i]=...;

3.”struct链表”

1
2
3
4
5
6
7
8
9
10
11
struct {
int child;
int fa;
int brother;
int present;
void init(){
child=fa=brother=present=0;
}
}tree[maxn];

加边: tree[i].init(); cin>>tree[i].present;

4.”有向树,用连接表”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int cnt=0;
int head[maxn];
int pre[maxn];
struct edge{
int v,next;
edge(){}
edge(int V,int NEXT):v(V),next(NEXT){}
}e[maxn<<1];

初始化:
void init()
{
cnt=0;
memset(head,-1,sizeof(head));
}

加边:
void addedge(int u,int v)
{
e[cnt]=e(v,head[u]);
head[u]=cnt++;
}

遍历:
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].v;
}