链式前向量

链式前向量:
链式前向量是一种存储边的信息的方法。
重点理解两个变量的含义:
next:表示与这个边起点相同的上一条边的编号
head[i]:表示以i为起点的最后一条边的编号
eg:一个5个点7条边的事例
1 2 1
2 3 2
3 4 3
1 3 4
4 1 4
1 5 6
4 5 7
对于1 2 1这条边:
edge[0].to=2; edge[0].next=-1; head[1]=0;
对于2 3 2这条边:
edge[1].to=3; edge[1].next=-1; head[2]=1;
对于3 4 3这条边:
edge[2].to=4; edge[2].next=-1; head[3]=2;
对于1 3 4这条边:
edge[3].to=3; edge[3].next=0; head[1]=3;
对于4 1 4这条边:
edge[4].to=1; edge[4].next=-1; head[4]=4;
对于1 5 6这条边:
edge[5].to=5; edge[5].next=3; head[1]=5;
对于4 5 7这条边:
edge[6].to=5; edge[6].next=4; head[4]=6;

总体代码如下:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1001;//最大的边数
int n,m;//n个点m条边 
struct node
{
	int v,w,next;//终点,权值,与这个边起点相同的上一条边的编号 
 }edge[maxn]; 
 int head[maxn];//以i为起点的最后一条边的编号 
 int cnt;//第cnt条边 
void init()
{
	for(int i=0;i<=n;i++)
	{
		head[i]=-1;
	}
	 cnt=0;//从第0条边开始 
 } 
void add_edge(int u,int v,int w)
{
 	edge[cnt].v=v;
 	edge[cnt].w=w;
 	edge[cnt].next=head[u];//第cnt条边相同起点的下一条边的编号是以u为起点的最后一条边的编号
 	head[u]=cnt++;
} 
int main()
{
	cin>>n>>m;
	init();//初始化第一条边 
	for(int i=1;i<=m;i++)//加边 
	{
		int u,v,w;
		cin>>u>>v>>w;
		add_edge(u,v,w);
	}
	for(int i=1;i<=n;i++)
	{
		cout<<i<<endl;
		for(int j=head[i];j!=-1;j=edge[j].next)
		{
			cout<<edge[j].v<<" "<<edge[j].w<<endl;
		}
		cout<<endl;
	}
	return 0;
 } 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值