【姜神向前星】-链式向前星(数组模拟邻接表)

请原谅我偷个懒。姜神神敲的链式向前星,很好懂,就直接转过来了。自己模仿着敲过,感觉好极了!

有的时候有的图可能比较稀疏而且点数较多,邻接矩阵存不下,所以就要用到邻接表。邻接表用vector数组比较方便,但是vector比较慢。所以就有了链式向前星。


#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

//链式向前星其实就是有n条链表,每条链表存的是所有相同起点的边。


const int maxn=1100;//点数
const int maxm=11000;//边数
struct xx
{
    int next,n,to;
}node[maxm];//每个结点存一条边,next表示与当前边起点一样的另一条边在弄的数组中的位置。to表示这条边的终点,n表示这条边的权值。所有的边都将存在这个node数组中。

int head[maxn];//head[i]表示从i点出发的链表的第一个节点在node数组中的位置。

int num=0;//当前已有边的个数。
void Add(int from,int to,int n)
{
    node[num].to=to;
    node[num].n=n;
    node[num].next=head[from];//当前结点的下一个点指向以前的头结点,新增节点从头部插入
    head[from]=num++;//当前结点变为头结点
}
void Use(int i)//遍历起点为i的链表
{
    int t=head[i];
    while(t!=-1)
    {
        cout<<"from "<<i<<"to "<<node[t].to<<"is "<<node[t].n<<endl;
        t=node[t].next;
    }
}
int main()
{
    int from,to,n;
    memset(head,-1,sizeof(head));
    memset(node,-1,sizeof(node));
    while(cin>>from>>to>>n,from&&to&&n)
    {
        Add(from,to,n);
    }
    int i;
    cin>>i;
    Use(i);
}

我还是贴上我自己敲的吧,毕竟自己的代码风格是最舒服的~

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;
const int maxn=1100000;
const int maxm=110000;

struct node
{
	int next,to,value;	
};

node edge[maxm];
int head[maxn];
int n,m,num;

void add_edge(int from,int to,int cost)
{
	edge[num].to=to;
	edge[num].value=cost;
	edge[num].next=head[from];
	head[from]=num;
	num++;
}

void show()
{
	int i,t;
	for(i=1;i<=n;i++)
	{
		t=head[i];
		while(t!=-1)
		{
			cout<<i<<"-->"<<edge[t].to<<" need "<<edge[t].value<<endl;
			t=edge[t].next;
		}
	}
}

int main()
{
	freopen("input.txt","r",stdin);
	int from,to,cost;
	while(cin>>n>>m)
	{
		memset(edge,0,sizeof(edge));
		memset(head,-1,sizeof(head));
		num=0;
		while(m--)
		{
			cin>>from>>to>>cost;
			add_edge(from,to,cost);
			add_edge(to,from,cost);
		}
		show();
	}
	return 0;
}


  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值