前向星

来源:互联网 发布:软件创新设计方案 编辑:程序博客网 时间:2024/04/30 19:25
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;


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


通俗:输入时head向下指,next向上指,输出时就变成head向上,next向下



const int maxn=1100;//点数
const int maxm=11000;//边数
struct xx
{
    int next,to;
}node[maxm];//每个结点存一条边,next表示与当前边起点一样的另一条边在弄的数组中的位置。to表示这条边的终点,n表示这条边的权值。
int head[maxn];//head[i]表示从i出发的点的链表的第一个点在node数组中的位置。
int num=0;//当前已有边的个数。
void Add(int from,int to)
{
    node[num].to=to;


    node[num].next=head[from];//当前结点指向以前的头结点
    //cout<<" to   "<<node[num].to<<"   next  "<<node[num].next<<endl;
    head[from]=num++;//当前结点变为头结点
   // cout<<"head"<<" "<<head[from]<<endl;
}
void Use(int i)//遍历起点为i的链表
{
    int t=head[i];
    while(t!=-1)
    {
       // cout<<"t"<<t<<endl;
       // cout<<"from "<<i<<"to "<<node[t].to<<endl;


        t=node[t].next;
        //cout<<"node[t]"<<t<<endl;
    }
}
int main()
{
    int from,to,n;
    memset(head,-1,sizeof(head));
    memset(node,-1,sizeof(node));
    while(cin>>from>>to,from&&to&&n)
    {
        Add(from,to);
    }
    int i;
    cin>>i;
    Use(i);
}

0 0
原创粉丝点击