zoukankan      html  css  js  c++  java
  • 前向星

    前向星是一种通过存储边信息的方式存储图的数据结构。它的构造方式非常简单,读入每条边的信息,将边存放在数组中,把数组中的边按照起点顺序排序。

    前向星就构造完了。

    由于涉及排序,前向星的构造时间复杂度与排序算法有关,一般情况下时间复杂度为O(mlogm)。空间上,需要两个数组,空间复杂度为O(m+n)。

    前向星的优点可以应对非常多的情况,可以储存重边,但不能直接判断两个顶点之间是否有边,而且排序需要浪费一些时间。

     

    #include <bits/stdc++.h>

    using namespace std;

    typedef long long LL;
    const int maxn = 100005;
    int head[maxn];
    struct node {//存边的结构数据
      int form;
      int to;
      int w;
    }edge[maxn];
    bool cmp(node a, node b) {//比较函数
      if(a.from == b.from && a.to == b.to) return a.w < b.w;
      if(a.from == b.from) return a.to < b.to;
       return a.from < b.from;
    }
    int main() {
      //freopen("in.txt","r",stdin);
      //freopen("out.txt","w",stdout);
      int n, m;
      cin >> n >> m;//读取数据
      for(int i = 0; i < m; i++) cin >> edge[i].form >> edge[i].to >> edge[i].w;
      sort(edge,edge+m,cmp);
      memset(head, -1, sizeof(head));
      head[edge[0].from] = 0;
      for(int i = 1; i < m; i++)
      if(edge[i].from != edge[i-1].from)
        head[edge[i].from] = i;
      for(int i = 1; i <= n; i++) {//遍历
        for(int k = head[i];edge[k].from == i && k < m; k++) {
          cout << edge[k].from << " "<< edge[k].to << " " << edge[k].w << endl;
        }
      }
    return 0;
    }

  • 相关阅读:
    [iOS UI进阶
    [iOS UI进阶
    [iOS基础控件
    [iOS基础控件
    [iOS基础控件
    [iOS基础控件
    为什么会使用内部临时表
    Django日志模块配置
    mysql join语句分析(一)
    mysql误删数据以及kill语句工作原理
  • 原文地址:https://www.cnblogs.com/creativepower/p/6664329.html
Copyright © 2011-2022 走看看