链式前向星存图(待修改)

链式前向星存图(待修改)

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100005;
struct NODE{
    int w;     //此条边的权值
    int e;     //此条边到达的点的编号
    int next;  //此条边到如1->3 表示3上一个如1->2这条边在edge中的位置
}edge[MAXN];

int cnt = 1;       //当前的edge已使用的位置,要从1开始
int head[MAXN];//用来存u这个点最后加入的边在edge中的位置

void add(int u, int v, int w)
{
    edge[cnt].w = w;
    edge[cnt].e = v;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}

int main()
{
    memset(head,0,sizeof(head));
	cnt=1;
	int n;
	cin>>n;
	int a,b,c;
	while(n--){
		cin>>a>>b>>c;
		add(a,b,c); //如果是无向图在加一个add(b,a,c);就行
	}
	int start;
	while(cin >>start && start != 0){
    for(int i=head[start];i!=0;i=edge[i].next)
	   cout<<start<<"->"<<edge[i].e<<" "<<edge[i].w<<endl;
	}
	return 0;
}
w 3 4 5 5 6 7
e 2 3 4 3 4 4
next 0 0 1 0 3 0
cnt 1 2 3 4 5 6
点的编号 1 2 3
head 2 4 5

head[i] 就存着编号为i点的最后加入的一个边在edge中的位置

发布了23 篇原创文章 · 获赞 6 · 访问量 837

猜你喜欢

转载自blog.csdn.net/wxy2635618879/article/details/89600687