vicuna-7b· LMSYS
Arena Human Preference 55K
Write C++ code to topologically sort a graph
- User
Write C++ code to topologically sort a graph
- Assistant
Here is an example of C++ code that uses the topological sorting algorithm to sort a graph represented by a vector of vectors:
#include <iostream> #include <vector> #include <queue> using namespace std; vector<vector<int>> graph; void addEdge(int u, int v, int weight) { // Add an edge between u and v with weight weight graph[u].push_back(weight); graph[v].push_back(weight); } void topologicalSort() { // Create a queue to store nodes in the order they should be processed queue<int> q; // Create a vector to store the parent of each node vector<int> parent; // Add a sentinel node (a node with a parent of -1) to the queue q.push(-1); // While the queue is not empty while (!q.empty()) { // Get the next node from the queue int u = q.front(); q.pop(); // If u has not been visited, mark it as visited and add it to the // list of parent nodes if (parent.empty()) { parent.push_back(u); cout << u << " "; } // Add the neighbors of u to the queue for processing for (int v : graph[u]) { if (parent.empty() || parent[parent.size() - 1] != u) { q.push(v); } } } } int main() { // Create the graph graph = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // Add edges to the graph addEdge(0, 1, 1); addEdge(0, 2, 2); addEdge(1, 3, 1); addEdge(2, 3, 2); addEdge(3, 4, 1); addEdge(4, 5, 2); addEdge(5, 6,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.