链式前向量:
链式前向量是一种存储边的信息的方法。
重点理解两个变量的含义:
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;
}