Source code for submission s1110

ants.cpp

  1. /*
  2.  * File: ants.c
  3.  * Author: cteam057
  4.  *
  5.  * Created on October 27, 2012, 12:39 PM
  6.  */
  7.  
  8. #include <cstdlib>
  9. #include <cstdio>
  10.  
  11. /*
  12.  *
  13.  */
  14.  
  15.  
  16. int cycles, l;
  17.  
  18. class Ant {
  19. public:
  20. double state, pos;
  21. int start, moved;
  22. Ant() {
  23. state = pos = start = moved = 0;
  24. }
  25. void operator=(Ant &b) {
  26. start=b.start;
  27. pos=b.pos;
  28. moved=b.moved;
  29. state=b.state;
  30. }
  31. };
  32.  
  33. int comp(const void* a, const void* b) {
  34. Ant* bx = (Ant *)b;
  35. Ant* ax = (Ant *)a;
  36. if(ax->start<bx->start) return -1;
  37. if(ax->start==bx->start) return 0;
  38. return 1;
  39. }
  40.  
  41.  
  42. int main(int argc, char** argv) {
  43. int a;
  44. int i, p, j;
  45. char d;
  46. Ant *ants;
  47.  
  48. while(scanf("%d %d", &l, &a)==2) {
  49. ants = new Ant[a];
  50. cycles=0;
  51. for(i = 0; i < a; i++) {
  52. scanf("%d %c", &p, &d);
  53. ants[i].start=p;
  54. ants[i].pos=p;
  55. if(d == 'L') {
  56. ants[i].state = -0.5;
  57. if(p>cycles) cycles = p;
  58. } else {
  59. ants[i].state = 0.5;
  60. if((l-p)>cycles) cycles = l-p;
  61. };
  62. }
  63.  
  64. qsort(ants, a, sizeof(Ant), comp );
  65.  
  66.  
  67. for(i = 0; i < cycles*2; i++) {
  68. ants[0].pos += ants[0].state;
  69. if(ants[0].state) ants[0].moved = 1; else ants[0].moved = 0;
  70. if(ants[0].pos<=0 || ants[0].pos>=l) ants[0].state=0;
  71. for(j = 1; j < a; j++) {
  72. ants[j].pos += ants[j].state;
  73. if(ants[j].state) ants[j].moved = 1; else ants[j].moved = 0;
  74. if(ants[j].pos==ants[j-1].pos) {
  75. ants[j].state*=-1;
  76. ants[j-1].state*=-1;
  77. }
  78. if(ants[j].pos<=0 || ants[j].pos>=l) ants[j].state=0;
  79. }
  80. }
  81.  
  82. if(cycles==0) {
  83. if(ants[0].state<0) ants[0].moved=1;
  84. for(i = 1; i<a-1; i++) {
  85. ants[i].moved=0;
  86. }
  87. if(ants[a-1].state>0) ants[a-1].moved=1;
  88. }
  89.  
  90. printf("The last ant will fall down in %d seconds - started at ", cycles);
  91. j = 0;
  92. for(i = 0; i < a; i++) {
  93. if(ants[i].moved&&j==0) {
  94. j++;
  95. printf("%d", ants[i].start);
  96. continue;
  97. }
  98. if(ants[i].moved&&j==1) {
  99. printf(" and %d", ants[i].start);
  100. break;
  101. }
  102. }
  103. printf(".\n");
  104.  
  105. delete ants;
  106. }
  107. return 0;
  108. }
  109.  
  110.