[英]Why space complexity of adjacency list representation is O(V+E) not O(E)?
#include<bits/stdc++.h>
using namespace std;
const int N=1e3;
vector <int> graph2[N];
int main(){
int n,m;
cin>> n>>m;
for(int i=0;i<m;i++){
int v1,v2;
cin>>v1>>v2;
graph2[v1].push_back(v2);
graph2[v2].push_back(v1);
}
for(int i=1;i<=6;i++){
for(int j=0;j<graph2[i].size();j++){
cout<<graph2[i][j]<<" ";
}
cout<<endl;
}
}
I am creating a adjacency list representation of a tree and using above code and found on the internet that its space complexity is O(V+E) not O(E) why?我正在创建树的邻接列表表示并使用上面的代码并在互联网上发现它的空间复杂度是 O(V+E) 而不是 O(E) 为什么? I am only using the vector for storing edges like--
我只使用向量来存储边缘,比如——
Input-
6 9
1 3
1 5
3 5
3 4
3 6
3 2
2 6
4 6
5 6
Output -
3 5
3 6
1 5 4 6 2
3 6
1 3 6
3 2 4 5
I am using only storing the one part as v1---v2 then only storing v2 and v1 is the index by default so why we are assuming v1 in our space complexity?我只使用将一个部分存储为 v1---v2 然后只存储 v2 并且 v1 是默认情况下的索引,那么为什么我们在空间复杂度中假设 v1 呢?
You're using a fixed N
and ignoring n
, which makes it look like the space complexity doesn't depend on the number of vertices (you are essentially saying "every graph has 1000 vertices").您使用的是固定的
N
并忽略了n
,这使得空间复杂度看起来不依赖于顶点的数量(您实际上是在说“每个图都有 1000 个顶点”)。
If you use a local vector<vector<int>> graph(n);
如果您使用局部
vector<vector<int>> graph(n);
, you see how the required space depends on n
. ,您会看到所需空间如何取决于
n
。
An adjacency list representation of a graph should be an array where every cell represents the name of a vertex of the graph, so you have an array of |V|图的邻接表表示应该是一个数组,其中每个单元格表示图的一个顶点的名称,所以你有一个数组 |V| size, then every element of the array is linked to a list that contains all the edges starting from the vertex represented by the cell of the array.
大小,则数组的每个元素都链接到一个列表,该列表包含从数组单元表示的顶点开始的所有边。
So, in total, you have an array of |V|所以,总的来说,你有一个数组 |V| size and |E|
尺寸和 |E| nodes representing all the edges starting from each vertex ( O(|V|+|E|) ).
表示从每个顶点开始的所有边的节点( O(|V|+|E|) )。
I hope I was clear.我希望我很清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.