-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadjacency_hashset.cpp
80 lines (67 loc) · 1.83 KB
/
adjacency_hashset.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
#define _CRT_SECURE_NO_DEPRECATE
#define __elshorpagi__ (ios_base::sync_with_stdio(false), cin.tie(NULL))
#define sz(v) ((int)((v).size()))
#define edl '\n'
/*-----Problem #2: Adjacency Hashset Representation--------------------*/
typedef vector<unordered_set<int>> GRAPH;
void add_directed_edge_hashset_reper(GRAPH &graph, int from, int to)
{
graph[from].insert(to);
}
void add_undirected_edge_hashset_reper(GRAPH &graph, int from, int to)
{
graph[from].insert(to);
graph[to].insert(from);
}
void print_adjaceny_edge_hashset(GRAPH &graph)
{
int len(sz(graph));
for (int from(0); from < len; ++from)
{
cout << "Node " << from << " has neighbors: ";
for (auto &to : graph[from])
cout << to << ' ';
cout << edl;
}
}
void Solve()
{
/*
Space Complexity is O(E)
Time complexity
- O(1) for add/remove/check edge
- O(Degree) for iterate on neighbors
Disadvantages
- No order guarantee for edges
- Impractical for multiple edges (we may do workarounds)
- Hash tables extra memory
- Like any hash tables, more caution to properly deal with the load (load factor)
*/
int nodes, edges;
cin >> nodes >> edges;
GRAPH graph(nodes);
for (int e(0); e < edges; ++e)
{
int from, to;
cin >> from >> to;
add_directed_edge_hashset_reper(graph, from, to);
// add_undirected_edge_hashset_reper(graph, from, to);
}
print_adjaceny_edge_hashset(graph);
cout << edl << "DONE" << edl;
}
int main()
{
__elshorpagi__;
// freopen("../test/input.txt", "r", stdin);
freopen("../test/output.txt", "w", stdout);
int tc(1);
// cin >> tc;
while (tc--)
Solve();
return (0);
}