Cod sursa(job #2650261)

Utilizator Razvan48Capatina Razvan Nicolae Razvan48 Data 17 septembrie 2020 20:20:17
Problema Secv Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.38 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const int NMAX = 5000;
const int MODULO = 666013;

class HashMap
{

public:
  HashMap() = default;

  void add(int key, int value)
  {
    auto pos = m_find(key);

    if (pos.second == -1)
    {
      hash_map[pos.first].push_back(make_pair(key, value));
    }
    else
    {
      hash_map[pos.first][pos.second].second = value;
    }
  }

  void remove(int key)
  {
    auto pos = m_find(key);

    if (pos.second == -1) return;

    hash_map[pos.first][pos.second] = hash_map[pos.first][hash_map[pos.first].size() - 1];
    hash_map[pos.first].pop_back();
  }

  int get(int key)
  {
    auto pos = m_find(key);

    if (pos.second == -1)
    {
      return -1;
    }
    else
    {
      return hash_map[pos.first][pos.second].second;
    }
  }

private:
  vector<pair<int, int>> hash_map[MODULO];

  pair<int, int> m_find(int key)
  {
    int hashed_key = key % MODULO;

    for (int i = 0; i < hash_map[hashed_key].size(); i++)
    {
      if (hash_map[hashed_key][i].first == key)
      {
        return make_pair(hashed_key, i);
      }
    }

    return make_pair(hashed_key, -1);
  }
};

int dp[1 + NMAX];
int last[1 + NMAX];
int v[1 + NMAX];
int c[1 + NMAX];

HashMap hm;

int main()
{
  ifstream in("secv.in");
  ofstream out("secv.out");
  int minim = NMAX + 1;

  int n;
  int lsir = 0;

  in >> n;
  for (int i = 1; i <= n; i++)
  {
    in >> v[i];
    if (hm.get(v[i]) != 1)
    {
      hm.add(v[i], 1);
      lsir++;
      c[lsir] = v[i];
    }
  }

  sort(c + 1, c + 1 + lsir);

  for (int i = 1; i <= lsir; i++)
  {
    hm.add(c[i], i);
    c[i] = i;
  }

  for (int i = 1; i <= n; i++)
  {
    // Normalizare la 1, 2, 3, 4, ... lsir
    v[i] = hm.get(v[i]);
  }

  for (int i = 1; i <= n; i++)
  {
    last[i] = 1 + NMAX;
  }

  for (int i = 1; i <= n; i++)
  {
    dp[i] = 1 + NMAX;
    last[v[i]] = i;

    if (v[i] == 1)
    {
      dp[1] = 1;
      continue;
    }

    if (last[v[i] - 1] < last[v[i]] && dp[v[i] - 1] < i)
    {
      dp[v[i]] = dp[v[i] - 1] + (i - last[v[i] - 1]);
      if (v[i] == c[lsir] && minim > dp[v[i]])
      {
        minim = dp[v[i]];
      }
    }
  }

  if (minim != NMAX + 1)
  {
    out << minim;
  }
  else
  {
    out << -1;
  }

  return 0;
}