Source code for submission s1298

ants.cpp

  1. #include <cstdio>
  2. #include <vector>
  3. #include <stack>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. inline bool is_inside(pair<int, int> place, int ants){
  8. return place.first >= 0 && place.first < ants && place.second < ants && place.second >= 0;
  9. }
  10.  
  11. inline bool have_conflict(pair<int, char> first, pair<int, char> second){
  12. return first.second == 'R' && second.second == 'L';
  13. }
  14.  
  15. inline void flip(pair<int, int> positions, vector<pair<int, char> >& vect){
  16. int x, y;
  17. x = positions.first;
  18. y = positions.second;
  19. vect[x].second = 'L';
  20. vect[y].second = 'R';
  21. }
  22.  
  23. inline int maximum(int first, int second){
  24. return (first < second) ? second : first;
  25. }
  26.  
  27.  
  28. int main() {
  29. int len, ants, place, distance, max, number;
  30. char face;
  31. while(scanf("%d %d", &len, &ants) == 2) {
  32. vector<pair<int, char> > vect;
  33. vector<int> position(2);
  34. distance = -1;
  35. number = 0;
  36. max = -1;
  37. for (int i = 0; i < ants; i++) {
  38. scanf("%d %c", &place, &face);
  39. vect.push_back(make_pair(place, face));
  40. distance = (face == 'L') ? place : (len-place);
  41. if (distance > max) {
  42. number = 1;
  43. max = distance;
  44. } else if (distance == max) {
  45. number = 2;
  46. }
  47. }
  48. sort(vect.begin(), vect.end());
  49. pair<int, int> current;
  50. stack<pair<int, int> > stack;
  51. stack.push(make_pair(0,1));
  52. while (!stack.empty()) {
  53. current = stack.top();
  54. stack.pop();
  55. if (is_inside(current, ants)){
  56. if (have_conflict(vect[current.first], vect[current.second])){
  57. flip(current, vect);
  58. stack.push(make_pair(current.second, current.second+1));
  59. stack.push(make_pair(current.first - 1, current.first));
  60. } else {
  61. stack.push(make_pair(current.second, current.second + 1));
  62. }
  63. }
  64. }
  65.  
  66. int ii = 0;
  67. while (ii < ants && vect[ii].second == 'L'){
  68. ii++;
  69. }
  70. if (ii == 0){
  71. position[0] = vect[0].first;
  72. } else if (ii == ants) {
  73. position[0] = vect[ants-1].first;
  74. } else {
  75. if (number == 2){
  76. position[0] = vect[ii-1].first;
  77. position[1] = vect[ii].first;
  78. } else {
  79. position[0] = maximum(vect[ii].first, vect[ii-1].first);
  80. }
  81. }
  82.  
  83.  
  84. if (number == 1){
  85. printf("The last ant will fall down in %d seconds - started at %d.\n", max, position[0]);
  86. } else {
  87. printf("The last ant will fall down in %d seconds - started at %d and %d.\n", max, position[0], position[1]);
  88. }
  89.  
  90. }
  91. return 0;
  92. }
  93.