以边操作为主的图用边集数组存储比较好,相比链式前向星,vector建图更容易懂。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
using LL = long long;
const int inf = 0x3f3f3f3f;
const int MAX_E = 1e5+5; // 最大边数
const int MAX_V = 1e4+5; // 最大节点数
int V, E; // 点、边
struct edge{ int to, w; };
vector<edge> G[MAX_E];
bool vis[MAX_V];
void input();
void Build(int x, int y, int w);
void _dfs(int s);
void dfs(int s); // 封装了memset
void bfs(int s);
int main()
{
input();
dfs(0);
cout << endl;
bfs(0);
return 0;
}
void Build(int x, int y, int w = 1)
{
edge e; e.to = y; e.w = w;
G[x].push_back(e);
}
void input()
{
int a,b,w;
edge e;
cin >> V >> E;
for (int i = 0; i < E; i++)
{
cin >> a >> b >> w; // 带权
//cin >> a >> b; // 不带权
Build(a, b