-
Notifications
You must be signed in to change notification settings - Fork 1
/
self_loops_solution.cpp
102 lines (89 loc) · 2.35 KB
/
self_loops_solution.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
g++ self_loops.cpp -o g
echo "2
1
4 5 1
0 3
3 1 4
3 0" | ./g
. . * . . .
. . . . . .
. * . . * *
* . . . . .
. * . * . .
* . . * . .
*/
#define _GLIBCXX_DEBUG
#define _SECURE_SCL 1
#include <vector>
#include <string>
#include <cassert>
#include <iterator>
#include <algorithm>
#include <istream>
#include <ostream>
#include <sstream>
#include <iostream>
// Adjacency list graph representation
typedef unsigned vertex_id;
typedef float edge_weight;
typedef std::vector<vertex_id> neighbors_t;
typedef std::vector<neighbors_t> graph;
// True iff there is an edge in g from u to v
inline bool has_edge(graph const& g, int u, int v)
{
return std::find(g[u].begin(), g[u].end(), v) != g[u].end();
}
// Return the number of vertices in g
inline std::size_t count_vertices( graph const& g )
{
return g.size();
}
// Background: to remove an element from a vector<T> v, invoke
// v.erase(x) where x is a vector<T>::iterator to the element
// Write a function delete_edge( g, u, v ) that uses v.erase with
// std::find to delete an edge from the graph
inline void delete_edge( graph& g, vertex_id u, vertex_id v )
{
assert( u < count_vertices( g ) );
neighbors_t::iterator e = g[u].end();
neighbors_t::iterator p = std::find( g[u].begin(), e, v );
if ( p != e )
g[u].erase( p );
}
// Write another function delete_self_loops( g ) that uses del_edge to
// delete all self-loops from the graph
inline void delete_self_loops( graph& g )
{
for ( vertex_id u = 0, n = count_vertices( g ); u != n; ++u )
delete_edge(g, u, u);
}
// Read a graph from input in adjacency list form.
void read_adjacency_list( graph& g )
{
for ( std::string line("x"); std::getline(std::cin, line); )
{
g.push_back( neighbors_t() );
std::stringstream s(line);
for ( vertex_id dst; s >> dst; )
g.back()
.push_back( dst );
}
}
// Write a g to output in adjacency matrix form.
void write_adjacency_matrix( graph const& g )
{
for ( vertex_id u = 0; u < g.size(); ++u )
{
for ( vertex_id v = 0; v < g.size(); ++v )
std::cout << ( has_edge( g, u, v ) ? "* " : ". " );
std::cout << std::endl;
}
}
int main( int argc, char *argv[] )
{
graph g;
read_adjacency_list( g );
delete_self_loops( g );
write_adjacency_matrix( g );
}