[La tercera sesión de la Escuela de verano de Niuke 2019] J cuestiona la gestión de LRU

Enlace de tema

Título

De acuerdo, en realidad no he leído esta pregunta antes. Mi compañero de equipo me dijo que esta pregunta es una pregunta simulada, y es el momento. Luego fui a ...
mantener aproximadamente una tabla lineal, y luego hay dos operaciones: insertar, insertar de consulta
, si este valor (cadena) ha aparecido antes, luego poner el valor anterior (cadena) en la tabla de la tabla lineal Fin (borre el original), pero el valor guardado (int) sigue siendo el valor anterior (int). Si no aparece, se inserta al final de la tabla. Si se encuentra que la longitud de la tabla lineal excede m después de la inserción, aparecerá el elemento del encabezado de la tabla.
Al consultar, si hay este valor (cadena), luego consulte el anterior o siguiente de este valor (cadena) de acuerdo con los requisitos, y luego devuelva su valor (int), si no (no hay anterior o siguiente), salida: Inválido

análisis

Al principio pensé que esto ... debería ser violento con STL (por supuesto, no demasiado violento). Elegí unordered_map + list.
Escuché que usar map obtendrá T, pero no lo he probado ...
unordered_map es una tabla hash y el mapa es un árbol rojo-negro En términos relativos, las horas de consulta, inserción y eliminación del mapa son relativamente estables, todas O (logN), mientras que la incertidumbre de tiempo de unordered_map es relativamente grande, la buena suerte es la consulta O (1), la mala suerte es O (N )

La complejidad
es constante en promedio y, en el peor de los casos, lineal con el tamaño del contenedor. ,
Tomado de cppreference

unordered_map usa string como índice, y la
lista de iteradores que guarda la lista guarda el orden de los valores, incluyendo string e int dos variables,
pero en realidad envié T primero, y luego agregué una lectura rápida a AC, y me sentí atascado A menudo...

Código AC

#include <bits/stdc++.h>

using namespace std;

typedef list<pair<int, string>>::iterator pl;
unordered_map<string, pl> ump;
list<pair<int, string>> lists;
char catchmessage[100];

struct ioss
{
    
    
#define endl '\n'
    static const int LEN = 20000000;
    char obuf[LEN], *oh = obuf;
    std::streambuf *fb;
    ioss()
    {
    
    
        ios::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);
        fb = cout.rdbuf();
    }
    inline char gc()
    {
    
    

        static char buf[LEN], *s, *t, buf2[LEN];
        return (s == t) && (t = (s = buf) + fread(buf, 1, LEN, stdin)), s == t ? -1 : *s++;
    }
    inline ioss &operator>>(long long &x)
    {
    
    
        static char ch, sgn, *p;
        ch = gc(), sgn = 0;
        for (; !isdigit(ch); ch = gc())
        {
    
    
            if (ch == -1)
                return *this;
            sgn |= ch == '-';
        }
        for (x = 0; isdigit(ch); ch = gc())
            x = x * 10 + (ch ^ '0');
        sgn && (x = -x);
        return *this;
    }
    inline ioss &operator>>(int &x)
    {
    
    
        static char ch, sgn, *p;
        ch = gc(), sgn = 0;
        for (; !isdigit(ch); ch = gc())
        {
    
    
            if (ch == -1)
                return *this;
            sgn |= ch == '-';
        }
        for (x = 0; isdigit(ch); ch = gc())
            x = x * 10 + (ch ^ '0');
        sgn && (x = -x);
        return *this;
    }
    inline ioss &operator>>(char &x)
    {
    
    
        static char ch;
        for (; !isalpha(ch); ch = gc())
        {
    
    
            if (ch == -1)
                return *this;
        }
        x = ch;
        return *this;
    }
    inline ioss &operator>>(string &x)
    {
    
    
        static char ch, *p, buf2[LEN];
        for (; !isalpha(ch) && !isdigit(ch); ch = gc())
            if (ch == -1)
                return *this;
        p = buf2;
        for (; isalpha(ch) || isdigit(ch); ch = gc())
            *p = ch, p++;
        *p = '\0';
        x = buf2;
        return *this;
    }
    inline ioss &operator<<(string &c)
    {
    
    
        for (auto &p : c)
            this->operator<<(p);
        return *this;
    }
    inline ioss &operator<<(const char *c)
    {
    
    
        while (*c != '\0')
        {
    
    
            this->operator<<(*c);
            c++;
        }
        return *this;
    }
    inline ioss &operator<<(const char &c)
    {
    
    
        oh == obuf + LEN ? (fb->sputn(obuf, LEN), oh = obuf) : 0;
        *oh++ = c;
        return *this;
    }
    inline ioss &operator<<(int x)
    {
    
    
        static int buf[30], cnt;
        if (x < 0)
            this->operator<<('-'), x = -x;
        if (x == 0)
            this->operator<<('0');
        for (cnt = 0; x; x /= 10)
            buf[++cnt] = x % 10 | 48;
        while (cnt)
            this->operator<<((char)buf[cnt--]);
        return *this;
    }
    inline ioss &operator<<(long long x)
    {
    
    
        static int buf[30], cnt;
        if (x < 0)
            this->operator<<('-'), x = -x;
        if (x == 0)
            this->operator<<('0');
        for (cnt = 0; x; x /= 10)
            buf[++cnt] = x % 10 | 48;
        while (cnt)
            this->operator<<((char)buf[cnt--]);
        return *this;
    }
    ~ioss()
    {
    
    
        fb->sputn(obuf, oh - obuf);
    }
} io;

int main()
{
    
    
#ifdef ACM_LOCAL
    freopen("./in.txt", "r", stdin);
    freopen("./out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(false);
    int t;
    io >> t;
    while (t--)
    {
    
    
        ump.clear();
        lists.clear();
        int q, m;
        io >> q >> m;
        string s;
        int op, val;
        for (int i = 0; i < q; i++)
        {
    
    
            pl cur;
            io >> op >> s >> val;
            if (op)
            {
    
    
                if (!ump.count(s))
                {
    
    
                    cout << "Invalid" << endl;
                    continue;
                }
                cur = ump[s];
                if (val == 1)
                {
    
    
                    cur++;
                    if (cur == lists.end())
                    {
    
    
                        cout << "Invalid" << endl;
                        continue;
                    }
                }
                else if (val == -1)
                {
    
    
                    if (cur == lists.begin())
                    {
    
    
                        cout << "Invalid" << endl;
                        continue;
                    }
                    cur--;
                }
                cout << (*cur).first << endl;
            }
            else
            {
    
    
                if (!ump.count(s))
                {
    
    
                    pair<int, string> newnode = make_pair(val, s);
                    lists.push_back(newnode);
                    pl tmp = lists.end();
                    tmp--;
                    ump.insert(make_pair(s, tmp));
                    if (lists.size() > m)
                    {
    
    
                        ump.erase(lists.front().second);
                        lists.pop_front();
                    }
                    cout << val << endl;
                    continue;
                }
                cur = ump[s];
                pair<int, string> newnode = make_pair((*cur).first, s);
                lists.push_back(newnode);
                pl tmp = lists.end();
                tmp--;
                ump[s] = tmp;
                lists.erase(cur);
                cout << newnode.first << endl;
            }
        }
    }
    return 0;
}

Supongo que te gusta

Origin blog.csdn.net/m0_43448982/article/details/97382483
Recomendado
Clasificación