-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.cpp
More file actions
97 lines (81 loc) · 2.28 KB
/
Copy pathgraph.cpp
File metadata and controls
97 lines (81 loc) · 2.28 KB
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
//Author: Zlata Dovbyk
//Laboratory Work 5. Variant 12
#include "graph.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <stack>
//universal error helpers
namespace Error {
bool report(const std::string& message) {
std::cerr << "\nError: " << message;
return false;
}
void print(const std::string& message) {
std::cerr << "\nError: " << message;
}
}
bool Graph::load_from_file(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
return Error::report("cannot open file.");
}
std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
std::string node1, node2, extra;
if (!(iss >> node1 >> node2) || (iss >> extra)) {
return Error::report("incorrect file format.");
}
adjacency_list[node1].insert(node2);
adjacency_list[node2].insert(node1);
}
if (adjacency_list.empty()) {
return Error::report("file is empty.");
}
return true;
}
int Graph::count_components_with_k_edges(int k) {
visited.clear();
int count = 0;
for (const auto& pair : adjacency_list) {
const std::string& node = pair.first;
if (visited.find(node) == visited.end()) {
int edge_count = 0;
dfs(node, edge_count);
if (edge_count / 2 == k) {
++count;
}
}
}
return count;
}
void Graph::dfs(const std::string& node, int& edge_count) {
std::stack<std::string> s;
s.push(node);
visited.insert(node);
while (!s.empty()) {
std::string current = s.top();
s.pop();
for (const auto& neighbor : adjacency_list[current]) {
++edge_count;
if (visited.insert(neighbor).second) {
s.push(neighbor);
}
}
}
}
void run_full_workflow(const std::string& filename) {
Graph graph;
if (!graph.load_from_file(filename)) {
return;
}
std::cout << "Enter K (components with exactly K edges will be counted): ";
int k;
if (!(std::cin >> k) || k < 0) {
Error::print("invalid value for K.");
return;
}
int result = graph.count_components_with_k_edges(k);
std::cout << "\n" << result;
}