Source code for submission s858

ants.cpp

  1. #include <stdio.h>
  2. #include <deque>
  3. #include <algorithm>
  4.  
  5. #define MAX(x, y) ((x) >= (y) ? (x) : (y))
  6. #define ABS(x) ((x) >= 0 ? (x) : (-(x)))
  7.  
  8. using namespace std;
  9.  
  10. struct Ant {
  11. int pos;
  12. char dir;
  13. };
  14.  
  15. bool cmp(const Ant &a, const Ant &b) {
  16. return a.pos < b.pos;
  17. }
  18.  
  19. int main() {
  20. int l, count, i;
  21.  
  22. newInstance:
  23. while (scanf("%d %d\n", &l, &count) != EOF) {
  24. deque<Ant> q;
  25.  
  26. int maxDist = -1;
  27. for (i = 0; i < count; ++i) {
  28. Ant ant;
  29. scanf("%d %c\n", &(ant.pos), &(ant.dir));
  30. q.push_back(ant);
  31.  
  32. if (ant.dir == 'R')
  33. maxDist = MAX(ABS(l - ant.pos), maxDist);
  34. else
  35. maxDist = MAX(ant.pos, maxDist);
  36. }
  37.  
  38. sort(q.begin(), q.end(), cmp);
  39.  
  40. while (q.size() > 2) {
  41. Ant a = q.front();
  42. Ant b = q.back();
  43. q.pop_front();
  44.  
  45. if (a.dir == 'R' && q.front().dir == 'L') {
  46. q.front().dir = 'R';
  47. } else if (a.dir == 'R' && q.front().dir == 'R') {
  48. size_t j = 1;
  49. while (j < q.size() - 1 && q[j].dir == 'R')
  50. ++j;
  51. if (q[j].dir == 'L') {
  52. q[j].dir = 'R';
  53. } else {
  54. printf("The last ant will fall down in %d seconds - started at %d.\n", maxDist, a.pos);
  55. goto newInstance;
  56. }
  57. }
  58.  
  59. if (q.size() == 2)
  60. goto twoOrOne;
  61.  
  62. q.pop_back();
  63.  
  64. if (b.dir == 'L' && q.back().dir == 'R') {
  65. q.back().dir = 'L';
  66. } else if (b.dir == 'L' && q.back().dir == 'L') {
  67. int j = q.size() - 2;
  68. while (j > 0 && q[j].dir == 'L')
  69. --j;
  70. if (q[j].dir == 'R') {
  71. q[j].dir = 'L';
  72. } else {
  73. printf("The last ant will fall down in %d seconds - started at %d.\n", maxDist, b.pos);
  74. goto newInstance;
  75. }
  76. }
  77. }
  78.  
  79. twoOrOne:
  80. if (q.size() == 1) {
  81. printf("The last ant will fall down in %d seconds - started at %d.\n", maxDist, q.front().pos);
  82. } else if (q.front().dir == 'R' && q.back().dir == 'R') {
  83. printf("The last ant will fall down in %d seconds - started at %d.\n", maxDist, q.front().pos);
  84. } else if (q.front().dir == 'L' && q.back().dir == 'L') {
  85. printf("The last ant will fall down in %d seconds - started at %d.\n", maxDist, q.back().pos);
  86. } else {
  87. int dist1 = q.front().pos;
  88. int dist2 = l - q.back().pos;
  89. int diff = dist1 - dist2;
  90. if (diff > 0)
  91. printf("The last ant will fall down in %d seconds - started at %d.\n", maxDist, q.front().pos);
  92. else if (diff < 0)
  93. printf("The last ant will fall down in %d seconds - started at %d.\n", maxDist, q.back().pos);
  94. else
  95. printf("The last ant will fall down in %d seconds - started at %d and %d.\n", maxDist, q.front().pos, q.back().pos);
  96. }
  97. }
  98.  
  99. return 0;
  100. }
  101.