#define _CRT_SECURE_NO_WARNINGS
#define _SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING
#include <bits/stdc++.h>
using namespace std;
typedef pair<long long, long long> p_t;
typedef list<p_t> lst_t;
typedef map<long long, lst_t::iterator> mp_t;
long long hs(char *s)
{
    long long r = 0;
    for (char *p = s; *p; p++)
        r = r * 10 + *p - '0';
    return r;
}
int main()
{
    char s[20];
    lst_t LRU;
    mp_t mp;
    long long T, Q, M, op, v, blkid;
    scanf("%lld", &T);
    while (T--)
    {
        LRU.clear(), mp.clear();
        scanf("%lld%lld", &Q, &M);
        while (Q--)
        {
            scanf("%lld%s%lld", &op, s, &v), blkid = hs(s);
            if (op == 0)
            {
                auto ite = mp.find(blkid);
                if (ite == mp.end())
                    mp[blkid] = LRU.insert(LRU.end(), {blkid, v});
                else
                {
                    p_t p = {blkid, ite->second->second};
                    LRU.erase(ite->second);
                    mp[blkid] = LRU.insert(LRU.end(), p);
                }
                printf("%lld\n", mp[blkid]->second);
            }
            if (op == 1)
            {
                auto ite = mp.find(blkid);
                if (ite == mp.end())
                    puts("Invalid");
                else
                {
                    auto ite2 = ite->second;
                    if (v == -1)
                        if (ite2 != LRU.begin())
                            printf("%lld\n", (--ite2)->second);
                        else
                            puts("Invalid");
                    if (v == 0)
                        if (ite2 != LRU.end())
                            printf("%lld\n", ite2->second);
                        else
                            puts("Invalid");
                    if (v == 1)
                        if (ite2 != LRU.end() && ++ite2 != LRU.end())
                            printf("%lld\n", ite2->second);
                        else
                            puts("Invalid");
                }
            }
            while (LRU.size() > M)
            {
                mp.erase(LRU.begin()->first);
                LRU.pop_front();
            }
        }
    }
    return 0;
}