这是链式前向星的结构体写法
其实就只一个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 );
}
}
}