zoukankan      html  css  js  c++  java
  • 三种存图方式(邻接矩阵,邻接表,链式前向星)

    #include<cstdio>
    #include<vector>
    #include<cstring>
    #include<algorithm>
    #include <iostream>
    using namespace std;
    const int MAXN=10;
    struct node
    {
        int to,cost;
    };
    int a[MAXN][MAXN];
    vector<node> v[MAXN];
    int n,m=5;  //m个顶点
    void init1()  //邻接矩阵
    {
        int i,j;
        for(i=1;i<=n;i++)
        {
            int x,y,z=1;  //z为权值,也可自己输入
            cin>>x>>y;
            a[x][y]=z;
        }
        for(i=1;i<=m;i++)
        {
            for(j=1;j<=m;j++)
               cout<<a[i][j]<<" ";
            cout<<endl;
        }
        return ;
    }
    void init2()   //邻接表
    {
        int i,j;
        for(i=1;i<=n;i++)
        {
            int x;
            node y;
            y.cost=1;   //cost为权值
            cin>>x>>y.to;
            v[x].push_back(y);
        }
        for(i=1;i<=m;i++)
        {
            for(j=0;j<v[i].size();j++)
                cout<<i<<" "<<v[i][j].to<<" "<<v[i][j].cost<<endl;
        }
        return ;
    }
    int cnt=0;
    int head[MAXN];
    struct Node
    {
        int to,cost,next;
    }edge[MAXN];
    void init3()   //链式前向星
    {
        int i,j;
        int start,endd,cost;
        memset(head,-1,sizeof(head));
        for(i=0;i<n;i++)
        {
            cost=1;
            scanf("%d%d",&start,&endd);
            edge[cnt].to=endd;
            edge[cnt].cost=cost;
            edge[cnt].next=head[start];
            head[start]=cnt++;
        }
        for(start=1;start<=m;start++)
            for(i=head[start];i!=-1;i=edge[i].next)
                printf("(%d %d)--> %d
    ",start,edge[i].to,edge[i].cost);
        return ;
    }
    int main()
    {
        cin>>n;   //输入n组数据
        init1();  //邻接矩阵
        init2();  //邻接表
        init3();  //链式前向星
        return 0;
    }
    
    
    
    
    
    样例:
    7
    1 2
    2 3
    3 4
    1 3
    4 1
    1 5
    4 5
    邻接矩阵运行结果
    0 1 1 0 1
    0 0 1 0 0
    0 0 0 1 0
    1 0 0 0 1
    0 0 0 0 0
    邻接表运行结果
    1 2 1
    1 3 1
    1 5 1
    2 3 1
    3 4 1
    4 1 1
    4 5 1
    链式前向星运行结果
    (1 5)-->1
    (1 3)-->1
    (1 2)-->1
    (2 3)-->1
    (3 4)-->1
    (4 5)-->1
    (4 1)-->1
  • 相关阅读:
    HDU2036 计算多边形的面积
    poj 3648 线段树成段更新
    线段树基本知识
    计算几何基本模板
    最长递增子序列问题—LIS
    poj 2503
    Python基础(5)_字符编码、文件处理
    Python基础(4)_字典、集合、bool值
    Python基础(3)_可变对象与不可变对象、列表、元祖和字典
    流程控制练习
  • 原文地址:https://www.cnblogs.com/jk17211764/p/9677348.html
Copyright © 2011-2022 走看看