Cod sursa(job #2650245)

Utilizator Razvan48Capatina Razvan Nicolae Razvan48 Data 17 septembrie 2020 20:06:16
Problema Secv Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.29 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 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++)
  {
    if (v[i] == c[1])
    {
      int st = i;
      int dr = i;
      int index = 1;

      for (int j = i + 1; j <= n && index < lsir; j++)
      {
        if (v[j] == c[index + 1])
        {
          index++;
          dr = j;
        }
      }

      if (index == lsir)
      {
        minim = min(minim, dr - st + 1);
      }
    }
  }

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

  return 0;
}