Cod sursa(job #1052703)

Utilizator bghimisFMI Ghimis Bogdan bghimis Data 11 decembrie 2013 18:23:13
Problema Deque Scor 25
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <utility>
using namespace std;

ifstream in ("deque.in");
ofstream out("deque.out");

vector<int>* getAllPositions(const unordered_multimap<int, int>& myHash, int minim)
{
  vector<int> *pozitii = new vector<int>;
  unordered_multimap<int, int>::const_iterator it = myHash.find(minim);

  while (it->first == minim)
    {
      pozitii->push_back(it->second);
      ++it;

      if (it == myHash.end())
	break;
    }

  // oare mere mai bine in heap ??
  return pozitii;  
}

int v[5000001];
int main()
{
  int n, k; in >> n >> k;

  unordered_multimap<int, int> myHash;
  for (int i = 1; i <= n; ++i)
    {
      in >> v[i];
      myHash.insert(make_pair(v[i], i));
    }

  vector<int> heap;
  for (int i = 1; i <= k; ++i)
    heap.push_back(-v[i]);
  make_heap(heap.begin(), heap.end());

  long long suma = 0;
  suma += -heap[0];

  for (int i = k + 1; i <= n; ++i)
    {
      heap.push_back(-v[i]);
      push_heap(heap.begin(), heap.end());
      
      int minim = -heap[0];
      vector <int> *pozitiiAleMinimului = getAllPositions(myHash, minim); 

      bool exista = false;
      for (vector<int>::iterator it = pozitiiAleMinimului->begin();
	   it != pozitiiAleMinimului->end();
	   ++it)
	if (*it >= i - k + 1 && *it <= i)
	  {
	    exista = true;
	    break;
	  }

      delete pozitiiAleMinimului;
      
      if (exista == true)
	suma += minim;
      else
	{
	  pop_heap(heap.begin(), heap.end());
	  --i;
	}
    }

  out << suma;

  return 0;
}