82 lines
2.2 KiB
C++
82 lines
2.2 KiB
C++
#include <iostream>
|
|
#include <vector>
|
|
#include <cassert>
|
|
#include <queue>
|
|
|
|
|
|
using namespace std;
|
|
|
|
class Graph {
|
|
public:
|
|
struct Edge {
|
|
int target_vertex, next_edge;
|
|
};
|
|
|
|
vector<Edge> edges;
|
|
vector<int> head_edges;
|
|
|
|
void init(int vertices_amount, int edges_amount = 1) {
|
|
edges.reserve(edges_amount);
|
|
head_edges.resize(vertices_amount, -1);
|
|
}
|
|
|
|
void add_edge(int source_vertex, int target_vertex) {
|
|
edges.push_back({target_vertex, head_edges[source_vertex]});
|
|
head_edges[source_vertex] = static_cast<int>(edges.size()) - 1;
|
|
}
|
|
|
|
void remove_edge(int source_vertex, int target_vertex) {
|
|
for (int edge = head_edges[source_vertex]; edge != -1; edge = edges[edge].next_edge) {
|
|
if (edges[edge].target_vertex == target_vertex) {
|
|
head_edges[source_vertex] = edges[edge].next_edge;
|
|
// edges.erase(edges.begin() + edge);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] bool accessible(int source_vertex, int target_vertex) const {
|
|
vector<bool> visited(head_edges.size(), false);
|
|
queue<int> q;
|
|
q.push(source_vertex);
|
|
visited[source_vertex] = true;
|
|
while (!q.empty()) {
|
|
int current_vertex = q.front();
|
|
q.pop();
|
|
for (int edge = head_edges[current_vertex]; edge != -1; edge = edges[edge].next_edge) {
|
|
int next_vertex = edges[edge].target_vertex;
|
|
if (next_vertex == target_vertex) {
|
|
return true;
|
|
}
|
|
if (!visited[next_vertex]) {
|
|
visited[next_vertex] = true;
|
|
q.push(next_vertex);
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
[[nodiscard]] bool cycled(int source_vertex) const {
|
|
return accessible(source_vertex, source_vertex);
|
|
}
|
|
};
|
|
|
|
int letters_amount, edges_amount;
|
|
Graph graph;
|
|
|
|
void add_edge_by_string(const string& s) {
|
|
assert(s.length() == 3);
|
|
graph.add_edge(s[0] - 'A', s[2] - 'A');
|
|
}
|
|
|
|
int main() {
|
|
ios::sync_with_stdio(false);
|
|
cin.tie(nullptr);
|
|
|
|
cin >> letters_amount >> edges_amount;
|
|
graph.init(letters_amount, edges_amount);
|
|
|
|
return 0;
|
|
}
|