您的位置:首页 > 理论基础 > 数据结构算法

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

2014-04-22 11:55 711 查看
请原谅我偷个懒。姜神神敲的链式向前星,很好懂,就直接转过来了。自己模仿着敲过,感觉好极了!



有的时候有的图可能比较稀疏而且点数较多,邻接矩阵存不下,所以就要用到邻接表。邻接表用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息