Advertisement
JosepRivaille

P69932: Seqüència més llarga

Mar 8th, 2016
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <set>
  4. using namespace std;
  5.  
  6.  
  7. int count_cons(set<int> &S1, set<int> &S2)
  8. //This function calculates how many sequences can we find.
  9. {
  10.     if (S1.empty() && S2.empty()) return 0;
  11.     else if (S1.empty() || S2.empty()) return 1;
  12.     else {
  13.       int count = 1, turn = 0, aux;
  14.       set<int>::iterator it1 = S1.begin(), it2 = S2.begin();
  15.       if (*it1 < *it2) {
  16.     aux = *it1;
  17.     ++turn;
  18.       }
  19.       else aux = *it2;
  20.       for(;;) {
  21.     if (turn%2 == 0) {
  22.       while (it1 != S1.end() && *it1 < aux) ++it1;
  23.       if (it1 == S1.end()) return count;
  24.       else {
  25.         ++count;
  26.         ++turn;
  27.         aux = *it1;
  28.         ++it1;
  29.       }
  30.     }
  31.     else {
  32.       while (it2 != S2.end() && *it2 < aux) ++it2;
  33.       if (it2 == S2.end()) return count;
  34.       else {
  35.         ++count;
  36.         ++turn;
  37.         aux = *it2;
  38.         ++it2;
  39.       }
  40.     }
  41.       }
  42.     }
  43. }
  44.  
  45.  
  46. int atoi(string &s)
  47. //String to integer converter
  48. {
  49.   int k = 0;
  50.   for (int i = 0; i < s.size(); ++i) {
  51.     k = (k*10)+(s[i] - '0');
  52.   }
  53.   return k;
  54. }
  55.  
  56.  
  57. int main()
  58. {
  59.   string s;
  60.   while (getline(cin,s)) {
  61.     set<int> S1, S2;
  62.     int n;
  63.     string aux = "";        // aux atoi
  64.     bool mto = false;       // More than one
  65.     for (int i = 0; i < s.size(); ++i) {
  66.       if (s[i] != ' ') {
  67.     aux.insert(aux.end(), 1, s[i]);
  68.       }
  69.       else {
  70.     n = atoi(aux);
  71.     if (n%2 == 0) S1.insert(n);
  72.     else S2.insert(n);
  73.     aux = "";
  74.     mto = true;
  75.       }
  76.     }
  77.     if (mto) {
  78.       n = atoi(aux);
  79.       if (n%2 == 0) S1.insert(n);
  80.       else S2.insert(n);
  81.       cout << count_cons(S1, S2) << endl;
  82.     }
  83.     else { //If the line is empty or have just 1 number have to print this.
  84.       if (s == "") cout << 0 << endl;
  85.       else cout << 1 << endl;
  86.     }
  87.   }
  88. }
  89.  
  90. //JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement