7/11/2015

11034 - Ferry Loading IV

Note:
1) The cars are loaded in the order of their arrival;
2) The ferry is initially on the left bank;
*3) If you get the error "deque iterator not dereferenceable" , make sure that you are not calling  pop()/front() on empty queue. 

Here's the code:

  1. #include<iostream>
  2. #include<queue>
  3. #include<string>
  4. using namespace std;
  5. int main()
  6. {
  7.         int laps , l, m, c, car, load;
  8.         string bank;
  9.         bool rightBank;
  10.        
  11.         cin >> c;
  12.        
  13.         for (int i = 0; i < c; i++){
  14.                 cin >> l >> m;
  15.                
  16.                 queue<int>Left, Right;
  17.                 load = 0;
  18.                 rightBank = 0;
  19.                 for (int j = 0; j < m; j++){
  20.                         cin >> car >> bank;
  21.                         if (bank == "left")
  22.                                 Left.push(car);
  23.                         else
  24.                                 Right.push(car);
  25.                 }
  26.                 laps = 0;  l *= 100;  
  27.                 while (!Left.empty() || !Right.empty()){
  28.                
  29.                        
  30.                         load = 0;
  31.                         if (rightBank){
  32.                                 while (!Right.empty() && load + Right.front() <= l)
  33.                                 {
  34.                                         load += Right.front(); Right.pop();
  35.                                 }
  36.                         }
  37.                         else{
  38.                                 while (!Left.empty() && load + Left.front() <= l)
  39.                                 {
  40.                                         load += Left.front(); Left.pop();
  41.                                 }
  42.                         }
  43.                         ++laps;
  44.                         rightBank = 1 - rightBank;
  45.                 }
  46.                
  47.                 cout << laps << endl;          
  48.         }
  49.         return 0;
  50. }

Sample input: 
9
1  4 
100 right
100 right
100 right
100 right
1  3
20 left
81 left
99 left
1  1
100 right
15 4
380 right
720 left
1340 right
1040 left

Sample output: 
6
5
2
4

1 comment: