链式前向星
前向星是一种特殊的边集数组,我们把边集数组中的每一条边按照起点从小到大排序,如果起点相同就按照终点从小到大排序,
但是利用前向星会有排序操作,如果用快排时间至少为O(nlog(n))
如果用链式前向星,加入next索引模拟指针指向下一个点的位置,就可以避免排序.
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define de(a) cout << #a << " = " << a << endl 4 #define rep(i, a, n) for (int i = a; i < n; i++) 5 #define per(i, a, n) for (int i = n - 1; i >= a; i--) 6 typedef long long ll; 7 typedef unsigned long long ull; 8 typedef pair<int, int> PII; 9 typedef pair<double, double> PDD; 10 typedef vector<int, int> VII; 11 #define inf 0x3f3f3f3f 12 const ll INF = 0x3f3f3f3f3f3f3f3f; 13 const ll MAXN = 1e3 + 7; 14 const ll MAXM = 1e5 + 7; 15 const ll MOD = 1e9 + 7; 16 const double eps = 1e-6; 17 const double pi = acos(-1.0); 18 int n, m; 19 struct Edge 20 { 21 int from, to, val; 22 int next; 23 } E[MAXM]; 24 int cnt = -1; 25 int head[MAXN]; 26 void add(int from, int to, int val) 27 { 28 E[++cnt].from = from; 29 E[cnt].to = to; 30 E[cnt].val = val; 31 E[cnt].next = head[from]; 32 head[from] = cnt; 33 } 34 int main() 35 { 36 memset(head, -1, sizeof(head)); 37 cin >> n >> m; 38 for (int i = 0; i < m; i++) 39 { 40 int u, v, val; 41 cin >> u >> v >> val; 42 add(u, v, val); //建边 43 } 44 int x = 1; //遍历从结点1出发的所有有向边 45 for (int i = head[x]; i != -1; i = E[i].next) 46 printf("from=%d to=%d v=%d\n", E[i].from, E[i].to, E[i].val); 47 return 0; 48 }