Напиши реализацию ориентированного взвешенного графа на c++
- User
Напиши реализацию ориентированного взвешенного графа на c++
- Assistant
Вот пример реализации ориентированного взвешенного графа на C++:
cpp#include <iostream> #include <vector> #include <map> using namespace std; class WeightedGraph { private: map<int, vector<pair<int, int>>> adjacencyList; public: void addEdge(int start, int end, int weight) { adjacencyList[start].push_back(make_pair(end, weight)); } void printGraph() { for (auto it = adjacencyList.begin(); it != adjacencyList.end(); ++it) { cout << "Vertex " << it->first << " is connected to:" << endl; for (int i = 0; i < it->second.size(); i++) { cout << " -> " << it->second[i].first << " with weight " << it->second[i].second << endl; } } } }; int main() { WeightedGraph graph; graph.addEdge(0, 1, 5); graph.addEdge(0, 2, 3); graph.addEdge(1, 2, 2); graph.addEdge(2, 3, 6); graph.printGraph(); return 0; } - User
- Assistant
Давайте создадим ориентированный взвешенный граф, используя классы ListNode и LinkedList для представления списка смежности:
cppclass WeightedGraphNode { public: int vertex; int weight; WeightedGraphNode* next; WeightedGraphNode(int v, int w) : vertex(v), weight(w), next(nullptr) {} }; class WeightedGraph { private: LinkedList* adjacencyList; public: WeightedGraph(int V) { adjacencyList = new LinkedList[V]; } void addEdge(int start, int end, int weight) { adjacencyList[start].addSorted(end, weight); } void printGraph(int V) { for (int i = 0; i < V; ++i) { cout << "Vertex " << i << " is connected to:" << endl; adjacencyList[i].print(); } } };