Trouble with Optimizing a Floyd-Warshall Implementation in C++ - Memory Usage Spike and Slow Performance
I'm migrating some code and Quick question that's been bugging me - I need help solving I tried several approaches but none seem to work... I've looked through the documentation and I'm still confused about I'm currently trying to implement the Floyd-Warshall algorithm in C++ to find the shortest paths between all pairs of vertices in a dense graph. However, I'm experiencing important performance optimization and a spike in memory usage when I try to run the algorithm on larger datasets. The graph has around 1000 vertices with edges between almost every pair, and the memory usage climbs to nearly 2GB, which seems excessive. Here's my implementation of the algorithm: ```cpp #include <iostream> #include <vector> #include <limits> using namespace std; const int INF = numeric_limits<int>::max(); void floydWarshall(vector<vector<int>>& graph) { int V = graph.size(); for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (graph[i][k] != INF && graph[k][j] != INF) { graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j]); } } } } } int main() { int V = 1000; vector<vector<int>> graph(V, vector<int>(V, INF)); // Initialize the graph with some edges // ... (initialization code) floydWarshall(graph); return 0; } ``` I initialize the graph with `INF` values for non-edges and run the algorithm, but it takes an excessively long time and the memory footprint is much larger than I expected. I've also tried using `std::vector` for dynamic memory allocation, but the question continues. Is there a more memory-efficient approach I can implement? Additionally, are there any optimizations I should consider to improve performance? I've read that for dense graphs like this, there might be better approaches, but I'm not sure what those would be. Any insights or suggestions would be greatly appreciated! Thanks in advance! I recently upgraded to C++ LTS. Any ideas how to fix this? I'm working on a service that needs to handle this. For reference, this is a production REST API. For context: I'm using C++ on Ubuntu 22.04.