vlatkovski

Map [jboi 2007]

Jun 22nd, 2017
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include <iostream> //cin, cout
  2. #include <string>   //string
  3. #include <map>      //map
  4. #include <sstream>  //istringstream
  5. #include <cmath>    //sqrt
  6. #include <iomanip>  //setprecision
  7.  
  8. using namespace std;
  9.  
  10. class Solution {
  11. private:
  12.     string str;
  13.     map<char, int> dir;
  14.     bool tracking = false;
  15.     int j = 0;
  16.     char cdir = '0';
  17.     float dist;
  18.  
  19.     bool isint(char &c) {
  20.         return c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9';
  21.     }
  22.     void add(int i) {
  23.         string num = str.substr(j, i - 1);
  24.         istringstream iss;
  25.         iss.str(num);
  26.         int inum;
  27.         iss >> inum;
  28.         dir[cdir] += inum;
  29.         //cout << "\tinum=" << inum << "; dir[" << cdir << "]=" << dir[cdir] << endl;
  30.     }
  31. public:
  32.     Solution(string strin) : str(strin) {
  33.         //parse the string and get the north, south, west, and east distances
  34.         for (unsigned int i = 0; i < str.length(); ++i) {
  35.             char c = str.at(i);
  36.  
  37.             //cout << "c=" << c << endl;
  38.  
  39.             if (tracking && i + 1 == str.length()) {
  40.                add(i);
  41.             }
  42.             if (!isint(c)) {
  43.                 if (tracking) {
  44.                     add(i);
  45.                     tracking = false;
  46.                 }
  47.                 if ((c == 'n' || c == 's' || c == 'w' || c == 'e')) {
  48.                     tracking = true;
  49.                     j = i + 1;
  50.                     cdir = c;
  51.                     //cout << "\tnow tracking; j=" << j << endl;
  52.                 }
  53.             }
  54.         }
  55.         //cout << "\tc[n]=" << dir['n'] << "; c[s]=" << dir['s'] << "; c[w]=" << dir['w'] << "; c[e]=" << dir['e'] << endl;
  56.  
  57.         //calculate the distance using pythagorean theorem
  58.         int v = dir['n'] - dir['s'];
  59.         v = v > 0 ? v : -v;
  60.         int h = dir['w'] - dir['e'];
  61.         h = h > 0 ? h : -h;
  62.         dist = sqrt(v*v + h*h);
  63.     }
  64.     float getDistance() {
  65.         return dist;
  66.     }
  67. };
  68.  
  69. int main() {
  70.     string str;
  71.     getline(cin, str);
  72.  
  73.     Solution solution(str);
  74.     float dist = solution.getDistance();
  75.     cout << std::fixed << std::setprecision(2) << dist << endl;
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment