搜索
查看: 4820|回复: 8
打印 上一主题 下一主题

[C/C++语言] cpp 使用结构体和vector来存储一棵树

[复制链接]
跳转到指定楼层
楼主
发表于 2014-11-3 15:10:54 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式
//cpp 使用结构体和vector来存储一棵树
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
struct node
{
    vector <int> son;
};
struct node e[1001];
int father[1001];
int main()
{
    int i,n,t1,t2;
    scanf("%d",&n);//n个顶点
    for(i=1;i<=n-1;i++)//n-1条边
    {
        scanf("%d %d",&t1,&t2);//t1是t2的爸爸
        e[t1].son.push_back(t2); //存储每个顶点有哪些儿子
        
        father[t2]=t1;//存储每个顶点的爸爸是谁
    }

    for(i=1;i<=n;i++)
    {
        printf("%d - ",i);
        vector <int> :: iterator it;
        for(it=e[i].son.begin(); it!=e[i].son.end(); it++)
        {
            printf("%d ",*it);
        }
        printf("\n");
    }

    return 0;
}
/*
9
3 5
3 6
1 2
1 3
1 4
6 7
6 8
6 9

*/
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

广播台
特别关注
快速回复 返回顶部 返回列表