Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. struct Semaphore
  7. {
  8. int distance;
  9. int red;
  10. int green;
  11. int redGreenCycle;
  12. };
  13.  
  14. int n, x, s, k;
  15. vector<Semaphore> semaphores;
  16. vector<int> solutions;
  17.  
  18. int gcd(int a, int b)
  19. {
  20. if (b == 0)
  21. return a;
  22.  
  23. return gcd(b, a % b);
  24. }
  25.  
  26. int lcm(int a, int b)
  27. {
  28. return a * b / gcd(a, b);
  29. }
  30.  
  31. int main()
  32. {
  33. ifstream fin("semarun.in");
  34. ofstream fout("semarun.out");
  35.  
  36. // read data and compute lcm of red + green intervals
  37. fin >> n >> x >> s >> k;
  38. Semaphore tmpSemaphore;
  39. int redGreenLcm = 1;
  40.  
  41. for (int i = 0; i < k; i++)
  42. {
  43. fin >> tmpSemaphore.distance >> tmpSemaphore.red >> tmpSemaphore.green;
  44. tmpSemaphore.redGreenCycle = tmpSemaphore.red + tmpSemaphore.green;
  45. redGreenLcm = lcm(redGreenLcm, tmpSemaphore.redGreenCycle);
  46. semaphores.push_back(tmpSemaphore);
  47. }
  48.  
  49. // check every moment of time between 0 and lcm-1
  50. int maxT = s - (int) ceil((float) n / x);
  51. for (int t = 0; t <= min(maxT, redGreenLcm - 1); t++)
  52. {
  53. bool isSolution = true;
  54. for (auto &semaphore:semaphores)
  55. {
  56. // check if any semaphore will indicate red colour
  57. int timeAtSemaphore = t + (semaphore.distance / x);
  58. if (timeAtSemaphore % semaphore.redGreenCycle < semaphore.red)
  59. {
  60. isSolution = false;
  61. break;
  62. }
  63. }
  64.  
  65. if (isSolution)
  66. solutions.push_back(t);
  67. }
  68.  
  69. // compute solution on intervals [lcm, 2*lcm-1] ... [y*lcm, maxT]
  70. int initialSolutionsCount = solutions.size();
  71. for (int i = 1; i <= maxT / redGreenLcm + 1; i++)
  72. {
  73. for (int j = 0; j < initialSolutionsCount; j++)
  74. {
  75. int newSol = redGreenLcm * i + solutions[j];
  76. if (newSol > maxT)
  77. break;
  78. solutions.push_back(newSol);
  79. }
  80. }
  81.  
  82. // write solutions
  83. fout << solutions.size() << endl;
  84. for (int &solution:solutions)
  85. fout << solution << " ";
  86.  
  87. return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement