简体   繁体   English

Memory 在 c++ 中分配动态二维布尔数组时超出限制

[英]Memory Limit Exceeded when allocating a dynamic 2D array of booleans in c++

I have tried to allocate a dynamic 2D array of booleans for implementing graph in C++.我试图分配一个动态的二维布尔数组来实现 C++ 中的图形。 Even though I have declared the graph globally and have done dynamic allocation using new operator yet I am getting memory limit exceeded error on codeforces.即使我已经在全局范围内声明了图表并使用 new 运算符完成了动态分配,但我在 codeforces 上收到 memory limit exceeded 错误。 I have gone through segmentation fault answers already but all answers ask for dynamic allocation to avoid this error which I have already done.我已经完成了分段错误的答案,但所有答案都要求动态分配以避免我已经做过的这个错误。

#include<bits/stdc++.h>
using namespace std;
bool ** g;
bool dfs_h(int n,int k,int src,int *vis){
vis[src]=1;
if(src==k) return true;
for(int i=1;i<=n;i++){
    if(g[src][i]&&!vis[i]){
        if(dfs_h(n,k,i,vis)) return true;
    }
}
return false;
}
bool dfs(int n,int k,int src){
int *vis=new int[n+1]{0};
bool ans=dfs_h(n,k,src,vis);
return ans;
}

main(){
int n,k;
cin>>n>>k;
g=new bool *[n+1];
for(int i=0;i<=n;i++) g[i]=new bool [n+1];
for(int i=1;i<=n;i++){
    for(int j=1;j<=n;j++) g[i][j]=false;
}
int buf;
for(int i=1;i<n;i++){
    cin>>buf;
    g[i][i+buf]=true;
}
bool ans=dfs(n,k,1);
for(int i=0;i<=n;i++) delete g[i];
delete [] g;
if(ans) cout<<"YES\n";
else cout<<"NO\n";
}

Let's think about this for the case of n=10000:让我们考虑一下 n=10000 的情况:

g=new bool *[n+1];

That will allocate 640064 bits on a 64-bit system.这将在 64 位系统上分配 640064 位。 Then:然后:

for(int i=0;i<=n;i++)
    g[i]=new bool [n+1];

That will allocate 800160008 bits (10001*10001*8).这将分配 800160008 位 (10001*10001*8)。

In total this is more than 95 GB of allocation to store 10001*10001 bits which is fundamentally only 12 GB.总共有超过 95 GB 的分配来存储 10001*10001 位,基本上只有 12 GB。

So the first thing you should do is change your storage strategy to use every bit, instead of just one bit per byte, and perhaps a single allocation instead of 10002 allocations.所以你应该做的第一件事是改变你的存储策略来使用每一位,而不是每个字节一个位,也许是一个分配而不是 10002 个分配。 Using a single std::vector<bool> bits(10001*10001) will accomplish this easily, you just need to write an indexing function like bool get(int x, int y) { return bits[x + y * 10001]; }使用单个std::vector<bool> bits(10001*10001)可以轻松完成此操作,您只需编写索引 function 就像bool get(int x, int y) { return bits[x + y * 10001]; } bool get(int x, int y) { return bits[x + y * 10001]; } . bool get(int x, int y) { return bits[x + y * 10001]; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM