图存储-前向星
//前向星是將所有的邊進行編號,每個節點u的邊集合通過head[u]來找到u的第一條邊, //再通過next[head[u]]依次遍歷節點u的所有邊。 int head[maxn];
int to[maxn*2];
int next[maxn*2];
int cnt = 0;//邊的編號
memset(head, -1, sizeof(head));inline void add(int x,int y){
to[cnt]=y,next[cnt]=head[x],head[x]=cnt++;
to[cnt]=x,next[cnt]=head[y],head[y]=cnt++;}inline void dfs(int u)
{int i;//從節點u的第一條邊開始,遍歷與u相連的所有邊for(i=head[u];i!=-1;i=next[i]) { dfs(to[i]);}
}
/*
head[i]: 以i為節點的邊集的第一條邊編號
next[i]:編號為i的邊集中的下一條邊編號,特定節點u的邊的編號連成一個鏈表
to[i]:編號為i的邊的終點
*/
//另一種實現
#include <iostream> #include <cstdio> using namespace std; const int maxn = 100; const int maxm = 100000; typedef struct edgenode {int to; //邊的終點int next; //當前下一條邊的編號int w; //邊的權值 }edgenode; int head[maxn]; //head[i]存放已i為起點的第一條邊 edgenode edge[maxm]; int edgenum = 1; int n = 0, m = 0; int init() {edgenum = 1;memset(head, 0, sizeof(head));//chu shi hua 0;return 0; } int outputmap(){for (int i = 1; i <= n; i++) {for (int k = head[i]; k != 0; k = edge[k].next) {printf("(%d --- > %d) == %d\n", i, edge[k].to, edge[k].w);}}return 0; } int main() {init();int a = 0, b = 0, c = 0;while (scanf("%d%d", &n, &m) == 2) {for (int i = 0; i < m; i++) {scanf("%d%d%d", &a, &b, &c);edge[edgenum].to = b;edge[edgenum].w = c;edge[edgenum].next = head[a];head[a] = edgenum;edgenum++;edge[edgenum].to = a;edge[edgenum].w = c;edge[edgenum].next = head[b];head[b] = edgenum;edgenum++;}outputmap();init();}return 0; }
?
//另一種實現
#include <iostream> #include <cstdio> using namespace std; const int maxn = 100; const int maxm = 100000; typedef struct edgenode {int to; //邊的終點int next; //當前下一條邊的編號int w; //邊的權值 }edgenode; int head[maxn]; //head[i]存放已i為起點的第一條邊 edgenode edge[maxm]; int edgenum = 1; int n = 0, m = 0; int init() {edgenum = 1;memset(head, 0, sizeof(head));//chu shi hua 0;return 0; } int outputmap(){for (int i = 1; i <= n; i++) {for (int k = head[i]; k != 0; k = edge[k].next) {printf("(%d --- > %d) == %d\n", i, edge[k].to, edge[k].w);}}return 0; } int main() {init();int a = 0, b = 0, c = 0;while (scanf("%d%d", &n, &m) == 2) {for (int i = 0; i < m; i++) {scanf("%d%d%d", &a, &b, &c);edge[edgenum].to = b;edge[edgenum].w = c;edge[edgenum].next = head[a];head[a] = edgenum;edgenum++;edge[edgenum].to = a;edge[edgenum].w = c;edge[edgenum].next = head[b];head[b] = edgenum;edgenum++;}outputmap();init();}return 0; }
?
轉載于:https://www.cnblogs.com/OUSUO/p/3805699.html
總結
- 上一篇: 负margin的移位参考线
- 下一篇: BZOJ1192: [HNOI2006]