Cod sursa(job #826959)

Utilizator BitOneSAlexandru BitOne Data 1 decembrie 2012 14:39:15
Problema Avioane Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.69 kb
#include <queue>
#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

const int NMAX = 100011;
deque< int > dQ;
vector< int > v;

inline long long int   _max(long long int x, long long int y)        {return x >= y ? x : y;}
inline bool            intersect(int i, int x1, int x2)              {return 1LL * v[x2] * (i - x2) >= 1LL * v[x1] * (i - x1);}
inline bool            intersectFaster(int maxIndex, int x1, int x2)
{
    if(maxIndex == x1)
    {
       return false;
    }
    return (1LL * v[x2] * x2 - 1LL * v[maxIndex] * maxIndex) / (v[x2] - v[maxIndex]) > (1LL * v[x1] * x1 - 1LL * v[maxIndex] * maxIndex) / (v[x1] - v[maxIndex]);
}

int main()
{
   long long int profit;
   int N, i, x;
   ifstream in("avioane.in");
   ofstream out("avioane.out");

   in >> N;
   profit = 0;
   switch(N)
   {
      case 2 : in >> profit;

      case 1 : in >> x;
               profit += x;
               out << profit << '\n';
               return EXIT_SUCCESS;
      default : copy(istream_iterator<int>(in), istream_iterator<int>(), back_inserter(v));
   }

   sort(v.begin(), v.end());
   profit = N * v[0];
   dQ.push_back(0);

   for(i = 1; i < N; ++i)
   {
      while(dQ.size() > 1)
      {
          if(intersect(i, dQ[0], dQ[1])) dQ.pop_front();
          else                        break;
      }
      profit = _max(profit, 1LL * v[i] * (N - i) + 1LL * v[dQ[0]] * (i - dQ[0]));
      if(v[i] == v[i-1]) continue;
      while(false == dQ.empty())
      {
          if(intersectFaster(dQ[0], dQ.back(), v[i])) dQ.pop_back();
          else                                  break;
      }
      dQ.push_back(i);
   }
   out << profit << '\n';

   return EXIT_SUCCESS;
}