图存储-前向星
//前向星是將所有的邊進(jìn)行編號(hào),每個(gè)節(jié)點(diǎn)u的邊集合通過head[u]來找到u的第一條邊, //再通過next[head[u]]依次遍歷節(jié)點(diǎn)u的所有邊。 int head[maxn];
int to[maxn*2];
int next[maxn*2];
int cnt = 0;//邊的編號(hào)
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;//從節(jié)點(diǎn)u的第一條邊開始,遍歷與u相連的所有邊for(i=head[u];i!=-1;i=next[i]) { dfs(to[i]);}
}
/*
head[i]: 以i為節(jié)點(diǎn)的邊集的第一條邊編號(hào)
next[i]:編號(hào)為i的邊集中的下一條邊編號(hào),特定節(jié)點(diǎn)u的邊的編號(hào)連成一個(gè)鏈表
to[i]:編號(hào)為i的邊的終點(diǎn)
*/
//另一種實(shí)現(xiàn)
#include <iostream> #include <cstdio> using namespace std; const int maxn = 100; const int maxm = 100000; typedef struct edgenode {int to; //邊的終點(diǎn)int next; //當(dāng)前下一條邊的編號(hào)int w; //邊的權(quán)值 }edgenode; int head[maxn]; //head[i]存放已i為起點(diǎn)的第一條邊 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; }
?
//另一種實(shí)現(xiàn)
#include <iostream> #include <cstdio> using namespace std; const int maxn = 100; const int maxm = 100000; typedef struct edgenode {int to; //邊的終點(diǎn)int next; //當(dāng)前下一條邊的編號(hào)int w; //邊的權(quán)值 }edgenode; int head[maxn]; //head[i]存放已i為起點(diǎn)的第一條邊 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; }
?
轉(zhuǎn)載于:https://www.cnblogs.com/OUSUO/p/3805699.html
總結(jié)
- 上一篇: 负margin的移位参考线
- 下一篇: BZOJ1192: [HNOI2006]