Cod sursa(job #1159649)

Utilizator MarcvsHdrMihai Leonte MarcvsHdr Data 29 martie 2014 19:27:16
Problema Gardieni Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.49 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

struct Interval {
  int a, b, c;
};

bool operator< (const Interval& left, const Interval& right) {
  if (left.b < right.b) {
    return true;
  } else if (left.b > right.b) {
    return false;
  } else {
    return left.c < right.c;
  }
}

std::vector<Interval> v;

int n, t, total = 0;

int main()
{
  std::ifstream in("gardieni.in");
  in >> n >> t;
  for (int i = 0; i < n; ++i) {
    int a, b, c;
    in >> a >> b >> c;
    Interval i;
    i.a = a;
    i.b = b;
    i.c = c;
    v.push_back(i);
  }
  in.close();

  std::sort(v.begin(), v.end());
  std::stack<Interval> s;
  for (int i = 0; i < n; ++i) {
    // Pop out elements from the stack.
    while (!s.empty() && s.top().b >= v[i].a && s.top().c > v[i].c) {
      Interval ii = s.top();
      s.pop();
      ii.b = v[i].a - 1;
      if (ii.a <= ii.b) {
        s.push(ii);
      }
    }

    // Now that you've cleared up everything that is more expensive and reaches
    // over the current interval, if there is anything left in the stack, then
    // it is either (a) less expensive, or (b) not touching the current
    // interval.
    if (!s.empty() && s.top().b >= v[i].a) {
      v[i].a = s.top().b + 1;
    }
    if (v[i].a <= v[i].b) {
      s.push(v[i]);
    }
  }

  while (!s.empty()) {
    total += (s.top().b - s.top().a + 1) * s.top().c;
    s.pop();
  }

  std::ofstream out("gardieni.out");
  out << total << std::endl;
  out.close();
  return 0;
}