Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

1.

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

void dfs(int node, const unordered_map<int, vector<int>>& graph, vector<bool>&


visited) {
visited[node] = true;
for (int neighbor : graph.at(node)) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited);
}
}
}

int countConnectedComponents(int n, const vector<pair<int, int>>& edges) {


unordered_map<int, vector<int>> graph;
for (const auto& edge : edges) {
graph[edge.first].push_back(edge.second);
graph[edge.second].push_back(edge.first);
}

vector<bool> visited(n + 1, false);


int components = 0;

for (int node = 1; node <= n; ++node) {


if (!visited[node]) {
dfs(node, graph, visited);
components++;
}
}

return components;
}

int main() {
int n, m;
cin >> n >> m;

vector<pair<int, int>> edges;


for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
edges.push_back(make_pair(x, y));
}

int components = countConnectedComponents(n, edges);


cout << components << endl;

return 0;
}

2.

#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>

using namespace std;

int shortestPath(int n, int m, int X, int Y, const vector<pair<int, int>>&


edges) {
unordered_map<int, vector<int>> graph;

for (const auto& edge : edges) {


graph[edge.first].push_back(edge.second);
}

vector<int> distance(n + 1, -1);


queue<int> q;
q.push(X);
distance[X] = 0;

while (!q.empty()) {
int node = q.front();
q.pop();

for (int neighbor : graph[node]) {


if (distance[neighbor] == -1) {
distance[neighbor] = distance[node] + 1;
q.push(neighbor);
}
}
}
return distance[Y];
}

int main() {
int n, m, X, Y;
cin >> n >> m >> X >> Y;

vector<pair<int, int>> edges;


for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y;
edges.push_back(make_pair(x, y));
}

int minEdges = shortestPath(n, m, X, Y, edges);


cout << minEdges << endl;

return 0;
}

You might also like