1. 程式人生 > >圖鄰接表陣列儲存

圖鄰接表陣列儲存

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int cnt = 0 ;
int head[100010]; 
struct st
{
	int u;
	int v;
	int w;
	int next;
}edge[100010];
void add(int u, int v, int w)
{
	edge[cnt].u = u;
	edge[cnt].v = v;
	edge[cnt].w = w;
	edge[cnt].next = head[u];
	head[u] = cnt++;
}
int main()
{
	int n,m,u,v,w;
	memset(head,-1,sizeof(head));
	cin>>n;
	for (int i=0; i<n; i++)
	{
		cin>>u>>v>>w;
		add(u,v,w);
	} 
	cin>>m;
	for (int i=head[m]; i!=-1; i=edge[i].next)
	{
		cout<<edge[i].u<<"->"<<edge[i].v<<":"<<edge[i].w<<endl; 
	}
	return 0;
}
如果是無向圖的話在新增一次add(v,u,w);即可