fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <thread>
  4. #include <mutex>
  5. #include <condition_variable>
  6.  
  7.  
  8. using namespace std;
  9.  
  10. int n;
  11. vector<vector<int> > D;
  12. int numberOfThreads = 4;
  13.  
  14. mutex m;
  15. condition_variable cv;
  16. int counter = 0;
  17.  
  18. void runThread(int x) {
  19. for (int k = 0; k < n; ++k) {
  20.  
  21. for (int i = x; i < n; i+= numberOfThreads) {
  22. for (int j = 0; j < n; ++j) {
  23. D[i][j] = min(D[i][j], D[i][k] + D[k][j]);
  24. }
  25. }
  26.  
  27. m.lock();
  28. counter++;
  29.  
  30. if(counter == numberOfThreads) {
  31. counter = 0;
  32. cv.notify_all();
  33. } else {
  34. unique_lock<std::mutex> lk(m);
  35. cv.wait(lk, [ ] { return counter == 0;});
  36. }
  37.  
  38. m.unlock();
  39.  
  40. }
  41. }
  42.  
  43. int main() {
  44. ios_base::sync_with_stdio(false);
  45. cin.tie(nullptr);
  46.  
  47. cin >> n;
  48. D.assign(n, vector<int>(n));
  49. vector<thread> myThreads(numberOfThreads);
  50.  
  51. for (int i = 0; i < n; ++i)
  52. for (int j = 0; j < n; ++j)
  53. cin >> D[i][j];
  54.  
  55. for(int i = 0; i < numberOfThreads; i++) {
  56. myThreads[i] = thread(runThread, i);
  57. }
  58.  
  59. for(int i = 0; i < numberOfThreads; i++) {
  60. myThreads[i].join();
  61. }
  62.  
  63. for (int i = 0; i < n; ++i) {
  64. for (int j = 0; j < n; ++j) {
  65. if (j > 0)
  66. cout << ' ';
  67. cout << D[i][j];
  68. }
  69. cout << endl;
  70. }
  71. }
Success #stdin #stdout 0s 4408KB
stdin
Standard input is empty
stdout
Standard output is empty