前式链向星

转自:https://blog.csdn.net/cryssdut/article/details/24300971

稍作修改

有的时候有的图可能比较稀疏而且点数较多,邻接矩阵存不下,所以就要用到邻接表。邻接表用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表示与当前边起点一样的另一条边在node的数组中的位置。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 <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#define INF 0x3f3f3f3f

using namespace std;

struct node
{
   int to,next,w;
}edge[10010];

int n,m;
int num=0;//记录边的总数
int vis[10010],head[10010];

int add(int from,int to,int w)//起点、终点、价值
{
   edge[num].to=to;
   edge[num].w=w;
   edge[num].next=head[from];
   head[from]=num++;
}

void show()
{
    int i,t;
	for(i=1;i<=n;i++)
	{
		t=head[i];
		while(t!=-1)
		{
		    printf("%d-->%d :%d\n",i,edge[t].to,edge[t].w);
			t=edge[t].next;
		}
	}
}
int main()
{
    memset(head,-1,sizeof(head));
    int i,j;
    scanf("%d%d",&n,&m);//n个点,m条边
    for(i=1;i<=m;i++)
    {
        int from,to,w;
        scanf("%d%d%d",&from,&to,&w);
        add(from,to,w);
        add(to,from,w);
    }
    show();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/AC_AC_/article/details/81407822