gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Привет
- User
Привет
- Assistant
Привет! Чем могу помочь?
- User
реши задачу на c++: Дан ориентированный граф. Необходимо найти все вершины, из которых достижима первая вершина.
- Assistant
Конечно, вот пример решения задачи на C++:
#include <iostream> #include <vector> #include <queue> using namespace std; // Функция для поиска всех вершин, из которых достижима первая вершина void findReachableVertices(vector<vector<int>>& graph, int numVertices) { vector<bool> visited(numVertices + 1, false); // Массив для отслеживания посещенных вершин vector<int> reachableVertices; // Вектор для хранения всех вершин, из которых достижима первая вершина queue<int> q; q.push(1); visited[1] = true; while (!q.empty()) { int currentVertex = q.front(); q.pop(); // Проверяем все смежные вершины for (int i = 0; i < graph[currentVertex].size(); i++) { int adjacentVertex = graph[currentVertex][i]; // Если смежная вершина еще не посещена, добавляем ее в очередь и помечаем как посещенную if (!visited[adjacentVertex]) { q.push(adjacentVertex); visited[adjacentVertex] = true; } } } // Записываем все вершины, из которых достижима первая вершина, в вектор for (int i = 1; i <= numVertices; i++) { if (visited[i]) { reachableVertices.push_back(i); } } // Выводим результат cout << "Все вершины, из которых достижима первая вершина:\n"; for (int i = 0; i < reachableVertices.size(); i++) { cout << reachableVertices[i] << " "; } } int main() { int numVertices, numEdges; cout << "Введите количество вершин и ребер: "; cin >> numVertices >> numEdges; vector<vector<int>> graph(numVertices + 1); // Матрица смежности для хранения графа cout << "Введите ребра графа:\n"; int from, to; for (int i = 0; i < numEdges; i++) { cin >> from >> to; graph[from].push_back(to); } findReachableVertices(graph, numVertices); return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.