zoukankan      html  css  js  c++  java
  • 树的存储

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    const int maxn = 100;//树的节点
    const int maxm = 10000;//树的边。
    int s[maxn];
    
    struct node {
        int tail;
        int next;
    }edge[maxm];
    
    void dfs(int u) {//搜索一遍。
        for(int i = s[u]; i != -1; i = edge[i].next) {
            printf("%d -> %d
    ", u, edge[i].tail);
            dfs(edge[i].tail);
        }
    }
    
    void output(int u) {//遍历
        for(int i = s[u]; i != -1; i = edge[i].next) {
            printf("%d - > %d
    ", u, edge[i].tail);
        }
    }
    
    int main()
    {
        int n;
        int from, to;//边的起点和重点。
        while(scanf("%d", &n)==1) {
            memset(s, -1, sizeof(s));
            for(int i = 0; i < n-1; i++) {
                scanf("%d%d", &from, &to);
                edge[i].tail = to;
                edge[i].next = s[from];
                s[from] = i;
            }
            int root = 1;//自己定义1为根节点。
            dfs(root);//从根节点开始搜索。
            for(int i = 1; i <= n; i++) {
                output(i);
            }
        }
        return 0;
    }
    /***
    Test:
    6
    1 2
    1 4
    2 3
    4 5
    4 6
    ***/
    


  • 相关阅读:
    CentOS命令找不到
    Docker原理之rootfs
    Docker原理之Namespace
    Docker原理之Cgroups
    Docker目录
    Docker基本使用
    Linux命令之防火墙
    Linux命令目录
    Rancher之主机添加
    oracle-decode函数用法
  • 原文地址:https://www.cnblogs.com/pangblog/p/3260530.html
Copyright © 2011-2022 走看看