c_cpp uva12345

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp uva12345相关的知识,希望对你有一定的参考价值。

#include <algorithm>
#include <cassert>
#include <iostream>
#include <set>
#include <string>
#include <vector>
using namespace std;

class dynamic_distinct
{
    enum { MAX_VALUE = 1000000 };

private:
    class pos_t // Like 'size_t' but provide the concept of '-1'.
    {
    public:
        pos_t() : m_pos(0)
        {
        }

        pos_t(size_t index) : m_pos(index + 1)
        {
        }

        operator size_t() const
        {
            return m_pos - 1;
        }

        bool operator <(const pos_t &rhs) const
        {
            return m_pos < rhs.m_pos;
        }

    private:
        size_t m_pos;
    }
    const pos_null;

public:
    dynamic_distinct(const vector<int> &list) : m_list(list), m_p(list.size()), m_q(1 + MAX_VALUE)
    {
        vector<pos_t> pre(1 + MAX_VALUE);

        for (size_t index = 0; index < m_list.size(); index++)
        {
            auto value = m_list.at(index);

            m_p.at(index) = pre.at(value);
            pre.at(value) = index;

            m_q.at(value).insert(index);
        }
    }

    void modify(size_t index, int value)
    {
        auto &here = m_p.at(index);
        {
            auto value = m_list.at(index);
            auto &q = m_q.at(value);

            auto &next = find_next(q, index);
            swap(here, next);
            q.erase(index);
        }
        assert(here == index);
        {
            m_list.at(index) = value;
            auto &q = m_q.at(value);

            auto &next = find_next(q, index);
            swap(here, next);
            q.insert(index);
        }
    }

    size_t query(size_t begin, size_t end) const
    {
        auto iter = m_p.begin();
        return count_if(iter + begin, iter + end, [begin](pos_t pos)
        {
            return pos < pos_t(begin);
        });
    }

private:
    pos_t &find_next(const set<size_t> &q, size_t index)
    {
        auto iter = q.upper_bound(index);
        if (iter != q.end()) return m_p.at(*iter);

        static pos_t dummy;

        auto last = q.rbegin();
        dummy = (last != q.rend()) ? pos_t(*last) : pos_null;
        return dummy;
    }

private:
    vector<int> m_list;

    vector<pos_t> m_p;
    vector<set<size_t>> m_q;
};

void test_case()
{
    size_t n, m;
    cin >> n >> m;

    vector<int> list(n);
    for (auto &x : list) cin >> x;

    dynamic_distinct dd(list);

    while (m--)
    {
        string cmd;
        size_t x, y;
        cin >> cmd >> x >> y;

        switch (cmd.at(0))
        {
        case 'M':
            dd.modify(x, y);
            break;
        case 'Q':
            cout << dd.query(x, y) << endl;
            break;
        }
    }
}

int main()
{
    test_case();
    return 0;
}

以上是关于c_cpp uva12345的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp uva10189

c_cpp uva10093

c_cpp uva12307

c_cpp uva681

c_cpp uva10101

c_cpp uva10107