• 图(邻接表链表和边表)


    最新版的请看本博客图的三种存储方式

    //邻接表 链表
    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include <limits.h> #define MAX_VERTEX_NUM 20 typedef int VertexType; typedef struct node{ VertexType adjvex; int weight; //权值 struct node *next; }EdgeNode; typedef struct vnode{ VertexType vertex; //顶点域 EdgeNode *firstedge; }VertexNode; typedef VertexNode AdjList[MAX_VERTEX_NUM]; typedef struct{ AdjList adjlist; int n,e; //顶点数和边数 }ALGraph; /* int Locate(ALGraph *G, int n){ int i; for(i=0; i<G->n; i++){ if(G->adjlist[i].vertex == n) return i; } return -1; }*/ void CreateALGraph(ALGraph *G){//建立有向图的邻接表 int i,j; int k; EdgeNode *s; scanf("%d%d", &G->n, &G->e); for(i=0; i<G->n; i++){ scanf("%d", &G->adjlist[i].vertex);//G->adjlist[i].vertex = getch(); G->adjlist[i].firstedge = NULL; //边表设置成空表 } for(k=0; k<G->e; k++){ scanf("%d%d", &i, &j); // i = Locate(G, i); j = Locate(G, j); //查找结点序号 s = (EdgeNode *)malloc(sizeof(EdgeNode)); scanf("%d", &s->weight); s->adjvex = j; //邻接点序号为j s->next = G->adjlist[i].firstedge; G->adjlist[i].firstedge = s; //无向图时加上 // s = (EdgeNode *)malloc(sizeof(EdgeNode)); // s->adjvex = i; // s->next = G->adjlist[j].firstedge; // G->adjlist[j].firstedge = s; } } void print(ALGraph *G){ EdgeNode *p; int i; for(i=0; i<G->n; i++){ printf("index %d VERTEX %d", i, G->adjlist[i].vertex); for(p = G->adjlist[i].firstedge; p; p = p->next){ printf("->\tVERTEX %d weight %d", p->adjvex, p->weight); } putchar('\n'); } } int main(){ freopen("d:\\my.txt", "r", stdin); ALGraph G; CreateALGraph(&G); print(&G); return 0; }

     //边表

    #include <stdio.h>
    
    #define MAXN 100
    #define MAXM 200
    
    int n, m;
    int first[MAXN];
    int u[MAXM], v[MAXM], w[MAXM], next[MAXM];
    
    void read_graph(int n, int m){  //有向图
        int i;
        for(i = 0; i < n; i++) first[i] = -1;
        for(i = 0; i < m; i++){
            scanf("%d%d%d", &u[i], &v[i], &w[i]);
            //插入到链表的首部
            next[i] = first[u[i]];
            first[u[i]] = i;
        }
    }
    
    int main(){
        freopen("d:\\my.txt", "r", stdin);
        int n, m, i, j;
        scanf("%d %d", &n, &m);
        read_graph(n, m);
        for(i=0; i<n; i++){ //输出
            printf("%d ", i);
            for(j=first[i]; j != -1; j = next[j])
                printf("->%d %d", v[j], w[j]);
            putchar('\n');
        }
        return 0;
    }
  • 相关阅读:
    lecture 11.4
    lecture 10.30
    boolean functions and beyon
    lecture10.21
    golang hex to string
    golang中 将string转化为json
    ubuntu16报错: add-apt-repository command not found
    ubuntu16的防火墙关闭
    ubuntu 16 解决错误 manpath: can't set the locale; make sure $LC_* and $LANG are correct
    go get 安装时报 (https fetch: Get https://golang.org/x/crypto/acme/autocert?go-get=1: dial tcp 220.255.2.153:443: i/o timeout)
  • 原文地址:https://www.cnblogs.com/tanhehe/p/2883510.html
Copyright © 2020-2023  润新知