zoukankan      html  css  js  c++  java
  • 邻接表

     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<iostream>
     4 using namespace std;
     5 const int maxn=1100;
     6 const int maxm=maxn*maxn/2;
     7 int n,m;
     8 int head[maxn],nxt[maxn],pnt[maxn],cost[maxn];
     9 int e;//e代表这些数组中的下标,便于录入和寻找某值
    10 void AddEdge(int u,int v,int c)
    11 {
    12     pnt[e]=v;//表示连接的点
    13     cost[e]=c;//该边的权值
    14     nxt[e]=head[u];//nxt的下标与pnt的下标相同,所以nxt存储着上一个被找出的与u连接的点的pnt下标,和上一个nxt的下标,当值为-1时,则没有了;
    15     head[u]=e++;//head存储着当前刚刚录入的pnt和nxt的下标,即存储着与u连接的目前最后出现的点的下标
    16 }
    17 int main()
    18 {
    19     while(~scanf("%d%d",&n,&m))
    20     {
    21         e=0;
    22         memset(head,-1,sizeof(head));
    23         for(int i=0; i<m; i++)
    24         {
    25             int u,v,c;
    26             scanf("%d%d%d",&u,&v,&c);
    27             AddEdge(u,v,c);
    28         }
    29         for(int u=1; u<=n; u++)//从前往后输出
    30         {
    31             printf("%d:",u);
    32             for(int i=head[u]; i!=-1; i=nxt[i])
    33                 printf("%d cost=%d",pnt[i],cost[i]);
    34             puts("");
    35         }
    36     }
    37     return 0;
    38 }
    39 /*
    40 模拟数据
    41 7 12
    42 1 2 24
    43 1 3 8
    44 1 4 15
    45 2 5 6
    46 3 5 7
    47 3 6 3
    48 4 7 4
    49 5 7 9
    50 6 5 2
    51 6 7 3
    52 6 4 5
    53 7 2 3
    54 */
  • 相关阅读:
    用python3实现linux的sed功能
    查找列表中指定的所有元素的位置
    Django分页
    python3中字典的copy
    Python中is和==的区别的
    python3的文件读写模式
    使用python3简单完成购物过程
    python3中str的函数
    第一篇
    《笑傲江湖》传剑摘录 有感而发
  • 原文地址:https://www.cnblogs.com/tianmin123/p/4788146.html
Copyright © 2011-2022 走看看