邻接矩阵与邻接表

本文探讨了如何使用STL和数组分别实现图的邻接矩阵和邻接表。首先介绍了使用STL构建邻接矩阵的方法,接着详细讲解了数组实现邻接表的思路,并给出了相关代码参考链接。

一、STL实现邻接矩阵与邻接表

1.邻接矩阵

int G[maxn][maxn];
memset(G,0,sizeof(G));
//有s到t的边,若为有向图则G[s][t]=1;
//若为无向图,则G[s][t]=1,G[t][s]=1;

2.邻接表

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=2005;
const int inf=2e9+10;
const int maxv=10005;

struct edge
{
    int to,cost;
};

vector<edge> G[maxv];

int main()
{
    int V,E;
    scanf("%d%d",&V,&E);
    for(int i=0;i<E;i++)
    {
        //从s向t连边
        int s,t,c;
        scanf("%d%d%d",&s,&t,&c);
        G[s].push_back((edge){t,c});  //important!!
        //如果是无向图,则需要再从t向s连边;
    }

    for(int i=0;i<V;i++)
    {
        printf("%d--> ",i);
        for(int j=0;j<G[i].size();j++)
            printf("%d,%d ",G[i][j].to,G[i][j].cost);
        cout<<endl;
    }
}
/*
5 6
0 1 1
2 1 2
1 3 3
3 0 4
4 3 6
3 2 5

0--> 1,1
1--> 3,3
2--> 1,2
3--> 2,5 0,4
4--> 3,6
*/

二、数组实现邻接表

参考:http://www.cnblogs.com/ahalei/p/3651334.html

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=110;

int u[maxn],v[maxn],w[maxn];
int first[maxn],next[maxn];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        first[i]=-1;
    for(int i=1;i<=m;i++)         //模拟邻接表;
    {
        scanf("%d%d%d",&u[i],&v[i],&w[i]);
        
        next[i]=first[u[i]];      //key!
        first[u[i]]=i;
    }

    for(int i=1;i<=n;i++)         //遍历邻接表;
    {
        int k=first[i];
        if(!u[k])  continue;
        printf("%d :",u[k]);
        while(k!=-1)
        {
            printf("\\%d %d\\",v[k],w[k]);
            k=next[k];
        }
        printf("\n");
    }

    return 0;
}
/*
测试数据:
4 5
1 4 9
4 3 8
1 2 5
2 4 6
1 3 7
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值