链式前向星建图

这是链式前向星的结构体写法

其实就只一个cnt当作边标记的 方法,每个点的所有边之间加了点联系。

加了点注释,感觉有助于帮助理解

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
#include <cmath>
#include <map>
#include <queue>
#include <algorithm>
#include <set>
#include <vector>
#include <stack>
#define Clear( x , y ) memset( x , y , sizeof(x) );
#define Qcin() std::ios::sync_with_stdio(false);
using namespace std;
typedef long long LL;
const int Maxn = 1e4 + 7;
const int MaxN = 2e5 + 7;
const int Inf = 1e9 + 7;

int N, M, st , ed , cnt;
struct edge{
	int Next;    //下一条边的存储下标
	int to;      //这条边的终点
	int w;       //这条边的终点
};
edge Edge[MaxN];
int head[Maxn];//head[i]表示以i为起点的第一条边
void AddEdge(int u , int v , int w){  //起点u, 终点v, 权值w
	Edge[++cnt].Next = head[u];       //相当于新来一个边,就把它压在u这个点的stack里,它是栈顶
	Edge[cnt].w = w;
	Edge[cnt].to = v;
	head[u] = cnt;    // u 的第一条边为当前边
}

void Print() {
    cin >> st >> ed;
    //st 起点 , ed 终点
    int NextPoint , w;
    for(int i = head[st] ; ~i ; i = Edge[i].Next){//i开始为第一条边,每次指向下一条(以-1为结束标志)
    	NextPoint = Edge[i].to;
    	w = Edge[i].w;
    }
}

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

int main() {
    cin >> N >> M;
    int u , v , w;
    for(int i = 1 ; i <= M ; i++) {
        cin >> u >> v >> w;
        AddEdge(u , v , w);
    }
    Print();
    return 0;
}

以前用的写法

贴一波代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
#include<set>
#include<map>
#include<ctime>
#include<iostream>
typedef long long LL;
using namespace std;
const int maxn = 1e5;
int n , m , all;
int pre[Maxn*2 + 5] ,last[Maxn +5],other[Maxn*2 + 5],cost[Maxn*2 + 5];
void Build( int u ,int v , int w){
	pre[++all] = last[u];
	other[all] = v;
	last[u] = all;
	cost[all] = w;
}
int main()
{
	int u , v , w;
	while( scanf("%d %d", &n , &m ) != EOF )
	{
		all = -1;
		memset( last , -1 , sizeof(last) );
		for( int i = 1 ; i <= m ; i++ )
		{
			scanf("%d %d %d",&u , &v ,&w);
			Build( u , v , w ) , Build( u , v , w );
		}
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值