链式前向星的实现

关于链式前向星dalao在这里已经讲得很清楚了,这里就贴个板子。

#include <bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxe = 1e6+6;
const int maxn = 1e6+6;
struct Edge
{
	int to, w, next;
	Edge() {}
	Edge(int to, int w, int next): to(to), w(w), next(next) {}
};
Edge edge[maxe];
int head[maxn];
int n, e;

void init()
{
	for(int i = 0; i < maxn; ++i)
		head[i] = -1;
}

void addEdge(int u, int v, int w, int id)
{
	edge[id] = Edge(v, w, head[u]);
	head[u] = id;
}

void traversal()
{
	for(int i = 0; i < n; ++i)
		for(int j = head[i]; ~j; j = edge[j].next) //~是按位取反,-1的二进制是111...1,按位取反后变为000...0,相当于 != -1
			cout << i << " -> " << edge[j].to << endl;
}

void read()
{
	cin >> n >> e;
	int u, v, w;
	for(int i = 0; i < e; ++i)
	{
		cin >> u >> v >> w;
		addEdge(u, v, w, i);
	}
}

int main()
{
	ios::sync_with_stdio(false);
   	cin.tie(0); cout.tie(0);
   	init();
   	read();
   	traversal();
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值