【问题标题】:How to store adjacency matrix of a graph using bitmap 2D array如何使用位图二维数组存储图形的邻接矩阵
【发布时间】:2014-11-28 07:49:27
【问题描述】:

我想存储一个非常大的图(大约 40k 个节点)的邻接矩阵。但是使用 int 和 char 数组,由于内存限制,我遇到了分段错误。使用 malloc 的动态分配在这里也失败了。任何人都可以建议一种使用位图二维数组实现此功能的方法吗? 到目前为止,这是我在 C 中的实现:

#include <stdio.h>
#include <stdlib.h>

int MAX = 50000;

void clustering(char adj[][MAX]);

int count_neighbour_edges(int temp[], int len, char adj[][MAX]);

int main()
{
   int nol = 0, i, j, k;    
   FILE *ptr_file1,*ptr_file2;

   struct community
   {
      int node;
      int clust;
   };
   struct community d;

   ptr_file1 = fopen("community.txt","r");

   if (!ptr_file1)
    return 1;

   while(fscanf(ptr_file1,"%d %d",&d.node, &d.clust)!=EOF)  //Getting total no. of nodes from here
   {
     nol++;
   }

   char adj[nol+1][nol+1];     //Getting segmentation fault here    

   struct adjacency
   {
       int node1;
       int node2;
   };
   struct adjacency a;

   ptr_file2 = fopen("Email-Enron.txt","r");

   if (!ptr_file2)
    return 1;




    while(fscanf(ptr_file2,"%d %d",&a.node1, &a.node2)!=EOF)
    {
       adj[a.node1][a.node2] = '1'; 
       adj[a.node2][a.node1] = '1'; 
    } 

    clustering(adj);
    return (0);
}

【问题讨论】:

  • 您可能想尝试将矩阵存储在堆上(使用 malloc)。至少在 64 位系统上,您需要大约 1.6 GB,这应该不是问题。将矩阵存储在堆栈上肯定会导致堆栈溢出。
  • @nwellnhof 我已经尝试过了。它没有用。
  • 怎么还不够?分配1.6G内存应该没问题。如果您在 linux 中工作,我认为 brk(2)sbrk(2) 应该允许您提高分配限制。或者,更简单的方法是使用mmap(2)。它允许您分配 looooooots 的内存页面。

标签: c arrays bitmap


【解决方案1】:

您可以尝试将数组放在 DATA 段中。为此,您可以在任何函数之外声明它,然后将该内存区域用作动态大小的二维数组:

char buffer[MY_MAX_SIZE];

int main()
{

...

    if ((nol+1)*(nol+1) > MY_MAX_SIZE) {
        exit(1);   // Too large to fit in buffer!
    }
    char (*adj)[nol+1] = buffer;     // Use the space in buffer as a dynamic 2-dimensional array. 

有点不直观的声明是因为nol的大小在编译时是未知的,所以我不能将buffer声明为你想要的大小的二维数组。

您需要为 MY_MAX_SIZE 确定一个适合问题大小并且您的平台可以处理的值,例如

#define MY_MAX_SIZE (40000L * 40000L)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多